I’m having problems with left bit shifts in Java returning incorrect values…
Take 108 << 60 for instance. The answer should be*:
124515522497539473408
Java is returning this value
-4611686018427387904
for this statement:
System.out.println(108L << 60L);
Why??? Both values are forced longs… so I see no reason why any bit values should be truncated. What am I missing here?
*Citation: Wolfram Alpha
You are shifting beyond the length of a
long(64 bits). 108 occupies seven bits, so108L << 60Lrequires 67 bits to represent it correctly. Actually, since it’s a signed type, you’d need 68 bits to avoid having it interpreted as a negative number.