posted 8 years ago
I have been experimenting with shifting bits around. For example, if I do
1 << 24
I get a number, when written out in bits is
11111111000000000000000000000000
However, I did this
1 << 32
and expected
00000000000000000000000000000000
However, I got this:
11111111111111111111111111111111
Why?
1 << 24
I get a number, when written out in bits is
11111111000000000000000000000000
However, I did this
1 << 32
and expected
00000000000000000000000000000000
However, I got this:
11111111111111111111111111111111
Why?
posted 8 years ago
That's because when you shift an int 32 times, it will really be shifted 0 times instead of 32 times.
Section 15.19 of the Java Language Specification explains this:
So, in the case of an int, only the lowest five bits of the shift distance are used. The lowest five bits of the number 32 are all 0, so the real shift distance is 0 (32 & 0x1f = 0).
Section 15.19 of the Java Language Specification explains this:
If the promoted type of the lefthand operand is int, only the five lowestorder bits of the righthand operand are used as the shift distance. It is as if the righthand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.
If the promoted type of the lefthand operand is long, then only the six lowestorder bits of the righthand operand are used as the shift distance. It is as if the righthand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x3f. The shift distance actually used is therefore always in the range 0 to 63, inclusive.
So, in the case of an int, only the lowest five bits of the shift distance are used. The lowest five bits of the number 32 are all 0, so the real shift distance is 0 (32 & 0x1f = 0).
We can walk to school together. And we can both read this tiny ad:
The WEB SERVICES and JAXRS Course
https://coderanch.com/t/690789/WEBSERVICESJAXRS
