1

Taking a memory array [1,2,3], is it possible to us shr/shl to make the array [2,3,1]?

1 Answer 1

1

shr and shl operations are used for bitwise shifting of individual values which is not what you want.

You should use inline assembly to load and store values at the corresponding memory locations. Here is an example:

pragma solidity ^0.8.0;

contract ArrayShift {
    function shiftArray(uint[] memory arr) public pure returns (uint[] memory) {
        uint arrayLength = arr.length;

        if (arrayLength > 1) {
            uint firstElement = arr[0];
            for (uint i = 0; i < arrayLength - 1; i++) {
                arr[i] = arr[i + 1];
            }
            arr[arrayLength - 1] = firstElement;
        }

        return arr;
    }
}
3
  • The example isn't shifting the array, it just copies each entry over itself (because it start with dst = src).
    – Ismael
    Apr 21 at 1:36
  • 1
    I updated my code
    – Saxtheowl
    Apr 21 at 1:58
  • Was trying to avoid a loop. Is it possible to encode the array and then shift?
    – Ryan Sea
    Apr 22 at 17:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.