Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting over type bit size

i am playing with shifting and i get troubled with one case:

    int maxint = Integer.MAX_VALUE;
    LOG.debug("maxint <<  31  --->  {} ({})", maxint << 31 , Integer.toBinaryString(maxint << 31 ));
    LOG.debug("maxint <<  32  --->  {} ({})", maxint << 32 , Integer.toBinaryString(maxint << 32 ));
    LOG.debug("maxint <<  33  --->  {} ({})", maxint << 33 , Integer.toBinaryString(maxint << 33 ));

and it prints:

maxint <<  31  --->  -2147483648 (10000000000000000000000000000000)
maxint <<  32  --->  2147483647 (1111111111111111111111111111111)
maxint <<  33  --->  -2 (11111111111111111111111111111110)

So the questions is if shift 31 leaves '1' at MSB then shift 32 should not move it out and return 0?

Going further i do the same starting with shift 31 result (which is Integer.MIN_VALUE) and shift by 1.

    int minInt = -2147483648;
    LOG.debug("minInt <<  1 --->  {} ({})", minInt << 1 , Integer.toBinaryString(minInt << 1 ));
    LOG.debug("minInt <<  2  ---> {} ({})", minInt << 2 , Integer.toBinaryString(minInt << 2 ));

and it prints:

minInt  <<  1 --->  0 (0)
minInt  <<  2  --->  0 (0)

which is what I expect.

like image 362
Michał Króliczek Avatar asked Jul 24 '26 04:07

Michał Króliczek


1 Answers

http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

and similarly six bits for long. This behavior is also allowed and commonly implemented in C and C++, though not required as in Java.

Also duplicate of Shift operator in Java bizarre program output which my first search missed.

like image 151
dave_thompson_085 Avatar answered Jul 25 '26 16:07

dave_thompson_085



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!