Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitshifting a long in Java

Tags:

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!

like image 476
Dori Avatar asked Mar 11 '14 15:03

Dori


1 Answers

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.

like image 94
Bathsheba Avatar answered Sep 20 '22 06:09

Bathsheba