Java-TypeCasting Question

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 is.

The second expression is a bit confusing. Great importance

10000000000000000000000000000000000 // 1, followed by 32 ZEROs, 33 bits in all

When it is forced into an int, how is it done as ZERO? Shouldn't he take the most important 1s as a sign bit and assume that the number is -2147483648? [REMOVAL OF THE CASE]

Also, when the double returned from Math.pow (4.294967296E9) is directly converted to int, why is it 2147483647?

I read the casting type and data types from the book, but the text does not explain much. I'm confused. Please explain why the second and third expressions give these results.

+3
3

, 32 , , 1 (, , ).

4294967296 = 0x100000000 ( ), 32 .

: , ​​int, , , int, .

+3

5.1.3 Java .

http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363

n , , . , , . .

int value = (int)(long)(Math.pow(2, 31)); // double to long to int
System.out.println(value); // Prints -2147483648

long lvalue = value; // int back to long
System.out.println(value); // Prints -2147483648 again

- , , , . /, float / , , .

+2

spec, 5.1.3. T - , , char int.

Narrowing the conversion of a signed integer to an integral type T simply discards everything except n bits of the least significant bit, where n is the number of bits used to represent type T. In addition to the possible loss of information about the value, a numerical value can lead to the sign of the resulting values ​​will differ from the sign of the input value.

You fall into the lower digits, which makes this case equal to 0.

0
source

Source: https://habr.com/ru/post/1780497/


All Articles