Another Shifty Challenge

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.

Comments

  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?

    ReplyDelete
  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.

    ReplyDelete
  3. I really needed to know ;) so after looking around I got some clarificatiion on the issue here:
    http://stackoverflow.com/questions/702607/in-java-when-using-bitshifts-why-does-1-32-1-31-1

    Good old SO.

    ReplyDelete

Post a Comment

Popular posts from this blog

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

System wide unique nanosecond timestamps

Unusual Java: StackTrace Extends Throwable