Java when shifting bits left, overflows dont disappear but appear back on other side

1
int i = 0x000000FF;
i = i << 24;

message = String.format("0x%08X", i);
// prints the message 0xFF000000

int i = 0x000000FF;
i = i << 32;

message = String.format("0x%08X", i);
// prints the message 0x000000FF

I was expecting the second one to print 0x00000000

What is going on?

java
bit-manipulation
asked on Stack Overflow Sep 16, 2017 by AlanSTACK

1 Answer

4

See Java Language Specification 15.19. Shift Operators:

If the promoted type of the left-hand operand is int, then 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.

So, i << 32 is the same as i << 0, i.e. no shift at all.

answered on Stack Overflow Sep 16, 2017 by Andreas

User contributions licensed under CC BY-SA 3.0