Another Shifty Challenge


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+" ");
-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.


  1. 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?

  2. Sometimes 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.

  3. I really needed to know ;) so after looking around I got some clarificatiion on the issue here:

    Good old SO.


Post a Comment

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

Comparing Approaches to Durability in Low Latency Messaging Queues