Questions about right shift and division operations

docs-soliditylang-org-en-v0.8.22, on page 54 and 55, there are two sentences
s1: x >> y is equivalent to the mathematical expression x / 2**y, rounded towards negative infinity.
s2: This means that int256(-5) / int256(2) == int256(-2).

take following example:
according to s1: int256(-5) >> 1 == int256(-5) / 2
but according to 2’complement representation, int256(-5) >> 1 is computed as following:
100…00101
111…11010
111…11011
right shift by 1
111…11101
100…00010
100…00011(result is -3)
so result is -3 which is not -2 as s2 described.
but the remix shows that int256(-5) >> 1 == -2.
could you give some comments? thanks.

1 Like

This gives -3:

contract Test {
    function func() external pure returns (int256) {
        return int256(-5) >> 1;
    }
}

And as an additional verification, this gives true:

contract Test {
    function func() external pure returns (bool) {
        return (int256(-5) >> 1) == int256(-3);
    }
}

Tested with HardHat, using Solc 0.8.13, optimization enabled, and optimization-runs set to 200.

BTW, I get the same results in Remix.

With regards to your claims:

You should have provided a link to those statements, but anyway, you must have misinterpreted s1 in a manner which has placed it in contradiction with s2.

So let’s start with s1:

It doesn’t say that x >> y is equivalent to x / 2**y.

It says that x >> y is equivalent to… the theoretical value of x / 2**y rounded towards negative infinity.

In your example, the theoretical value of -5 / 2 is -2.5.

And when rounded towards negative infinity, you get -3.

With regards to s2, your “this means” part is completely out of context here, because it obviously doesn’t appear immediately after s1, but at some other place in the documentation.

And as explained above, it doesn’t contradict s1, because the latter doesn’t claim that shift right and division by a power of 2 are equivalent operations.

More specifically, when dealing with negative operands, they are NOT equivalent operations (though s1 doesn’t state that fact explicitly).

Thank you for the detailed explanation and code examples. I get it too.

1 Like