6

I've seen this operator used in one of Mikhail Vladimirov's articles:

function mostSignificantBit(uint x) public pure returns (uint r) {
    require (x > 0);
    if (x >= 2**128) { x >>= 128; r += 128; }
    if (x >= 2**64) { x >>= 64; r += 64; }
    if (x >= 2**32) { x >>= 32; r += 32; }
    if (x >= 2**16) { x >>= 16; r += 16; }
    if (x >= 2**8) { x >>= 8; r += 8; }
    if (x >= 2**4) { x >>= 4; r += 4; }
    if (x >= 2**2) { x >>= 2; r += 2; }
    if (x >= 2**1) { x >>= 1; r += 1; }
}

What is the difference between the normal shift operator >> and >>=?

1 Answer 1

16

>> and << operators are the shift operators.

From Solidity docs:

The result of a shift operation has the type of the left operand, truncating the result to match the type. Right operand must be unsigned type. Trying to shift by signed type will produce a compilation error.

  • For positive and negative x values, x << y is equivalent to x * 2**y.
  • For positive x values, x >> y is equivalent to x / 2**y.
  • For negative x values, x >> y is equivalent to (x + 1) / 2**y - 1 (which is the same as dividing x by 2**y while rounding down towards negative infinity).

But, >>= and <<= operators work like += or -=.

  • x >>= 1 is equivalent to x = x >> 1.
  • x <<= 1 is equivalent to x = x << 1.

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.