0

I working on in-line assembly in the smart contract.

function rightShift(uint256 x) public pure returns (uint256 result) {
       assembly {
          result := shr(x,1)
       }
    }

Above function always return zero. Am I doing something wrong or it’s bug?

2 Answers 2

1

Always double-check the documentation.

shr(x, y) logical shift right y by x bits

With your notation, you are effectively shifting 1 by x bits to the right. For any non-zero value, the result will be zero.

You probably meant to write :

function rightShift(uint256 x) public pure returns (uint256 result) {
   assembly {
      result := shr(1,x)
   }
}
2

Let's take a look at the definition of the shr Yul instruction:

shr(x, y): logical shift right y by x bits

Your function always returns 0 because you are shifting by x (your variable x) bits, not by 1 bit.

To make it work, you have to rewrite it like this:

function rightShift(uint256 x) public pure returns (uint256 result) {
    assembly {
        result := shr(1, x)
    }
}

Your Answer

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

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