Overview
Shifting has lots of edge cases. Some particular to Java.
Over shifting
In C the expression
n << 64 and
n >> 64 would always be 0, but in Java it will always be
n This is because the shifted value is mod'ed by the number of bits.
A puzzle
If the following program
for (int i = -200; i < 200; i++)
if (i >>> i == 1)
System.out.print(i+" ");
prints
-193 -161 -129 -97 -65 -33 -1 37 70 102 135 167 199
What do you get if you change the type to
long?
See if you can work it out without running the code.
This is seriously messed up... Would hate to be the person having subtle bugs caused by this! I wonder why they did it this way? Surely it can't be for performance because all CPUs have shift instructions, right?
ReplyDeleteSometimes people do things this way because they want to appear clever. Sometimes, they do it by accident. I agree that I can't see any performance advantage.
ReplyDeleteI really needed to know ;) so after looking around I got some clarificatiion on the issue here:
ReplyDeletehttp://stackoverflow.com/questions/702607/in-java-when-using-bitshifts-why-does-1-32-1-31-1
Good old SO.