0

I'm playing around with bit manipulation in Java and I'm having a problem setting the 40th bit of a Long variable. When I do that, it just circles back to the 8th bit. So, that to me means that it is 32bit (instead of 64). However, my understanding is that Long/long is 2^64 in Java. I'm probably missing something here.

Here's the test code I've been toying around with in code.sololearn.com

   Long k = 256L; 
   Long x = Long.valueOf((1 << 40));

   System.out.println(x);

The above code returns 256.

vapurrmaid
  • 2,287
  • 2
  • 14
  • 30
KMC
  • 1,677
  • 3
  • 26
  • 55

1 Answers1

2

1 << 40 is an int-expression (and will effectively lead to 1 << (40 % 32) = 1 << 8, which evaluates to 256). Try using 1L << 40.

Here is an Ideone demo.

Turing85
  • 18,217
  • 7
  • 33
  • 58