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?
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 value0x1f
(0b11111). The shift distance actually used is therefore always in the range0
to31
, inclusive.
So, i << 32
is the same as i << 0
, i.e. no shift at all.
User contributions licensed under CC BY-SA 3.0