Bitshifting a long in Java

Dori picture Dori · Mar 11, 2014 · Viewed 11.7k times · Source

Im sure this is an easy one for whoever sees it first!

Why in Java does code like

   long one = 1 << 0;
   long thirty = 1 << 30;
   long thirtyOne = 1 << 31;
   long thirtyTwo = 1 << 32;

   System.out.println(one+" = "+Long.toBinaryString(1 << 0));
   System.out.println(thirty+" = "+Long.toBinaryString(1 << 30));
   System.out.println(thirtyOne+" = "+Long.toBinaryString(1 << 31));
   System.out.println(thirtyTwo+" = "+Long.toBinaryString(1 << 32));

print

1 = 1
1073741824 = 1000000000000000000000000000000
-2147483648 = 1111111111111111111111111111111110000000000000000000000000000000
1 = 1

This does not make sense to me. long is a 64 bit number - whereas it seems to act like an int in the above. I know bitshifted bytes undergo int promotion but I dont see whats going on in this case.

Any pointers on whats going on here would be good :)

Thx

EDIT: thanks for all the answers - i realised what was going on as soon as I clicked 'submit' but SO went into readonly mode and I couldnt delete! Many thanks!

Answer

Bathsheba picture Bathsheba · Mar 11, 2014

It's because 1 is an int literal, so << is applied to an integer. The result is cast to a long, but by then it's too late.

If you write 1L << 32, etc., then all will be well. L is used to denote a long literal.