long a = (long)Math.pow(2, 32);
// a = 4294967296 :)
long a = (int)(long)Math.pow(2, 32);
//a = 0 ?!
long a = (int)Math.pow(2, 32);
//a = 2147483647 WTF??!!!
The first expression is obvious. a is printed as it is.
The second expression is a bit confusing. The large value is
100000000000000000000000000000000 // 1 followed by 32 ZEROs, 33 bits in all
When it is forced into an int, how is it taken as ZERO? Shouldn't it take the most significant 1 as sign bit and think that the number is -2147483648 ? [DOUBT CLEARED]
Also, when the double returned from Math.pow (4.294967296E9) is directly cast into int, why is it 2147483647?
I am reading up type casting and data types from a book but the text doesn't explain much. I am confused. Please explain why the second and third expression produce those results.
解决方案
No, since it truncates everything past the first 32 bits as far as I know -- so it has no idea about the 1 at the beginning (or rather, at the end).
4294967296 = 0x100000000 (in hexadecimal), and taking only the first 32 bits gives you zero.
Edit: I actually think the other one has to do with a special cast from floating-point to int, that's not the same as going through a long and then an int, since it's a completely different kind of cast to the processor.