Solidity Assembly – Troubleshooting Right Shift Not Working in Inline Assembly

assemblysolidityyul

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?

Best Answer

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)
   }
}
Related Topic