1

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

2
  • 3
    Hmm... what's the largest value a long can hold? Commented Apr 8, 2012 at 4:41
  • I believe it's in the quadrillions? Commented Apr 8, 2012 at 18:15

3 Answers 3

4

You are shifting beyond the length of a long (64 bits). 108 occupies seven bits, so 108L << 60L requires 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.

Sign up to request clarification or add additional context in comments.

Comments

1

108 is 7 bits, so << 60 is 67 bits number.

Comments

1

The number that represents 108L << 60 is too large to be represented as a long. So you are getting overflow, and losing the high order bits.

If you want to represent numbers this big (without truncation) the simplest was is to use BigInteger.

Incidentally, the 2nd operand of a shift operator doesn't need to be a long. The actual shift count is calculated by truncating the operand to a number in the range 0 to 63 (for a long shift) - see JLS 15.19.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.