Java: double to float type is converted to a larger value to give ‘infinity’

Suppose I have a variable of type double with some random large values:

double d = 4786777867867868654674678346734763478673478654478967.77;

Now, if I try to convert it to float at some point in the program, the output shows "infinity" (in the eclipse IDE):

float f = (float)d;    // inifinty
byte b = (byte)d;      // some valid value
short s = (short)d;    // some valid value
int i = (int)d;        // some valid value

Someone can give me any valid answer, how is it not just for float data type conversion?

Solution

Let's look at the result of converting this large double to each of the other numeric primitive types:

double d = 4786777867867868654674678346734763478673478654478967.77;
    System.out.printf("float  %f\n",(float)d);
    System.out.printf("long   %d\n",(long)d);
    System.out.printf("int    %d\n",(int)d);
    System.out.printf("short  %d\n",(short)d);
    System.out.printf("byte   %d\n",(byte)d);

Output:

float Infinity
long  9223372036854775807
int   2147483647
short -1
byte  -1

float

From JLS:

Basically, IEEE 754 mandates this behavior IEEE 754 reserves a specific bit pattern to represent infinity and defines all floating-point operations involving this value

Long & Interpretation

JLS points out that when the original conversion from double to long or int is narrowed, if the value is too large to fit the range (64 or 32-bit signed integer), the maximum representable value long should be used MAX_ Value and integer MAX_ VALUE;

Short & bytes

When converting a double to short or byte, first cast the number to int. using the above rules, and then convert it from int to short or byte by discarding all bits except the N lowest bits (16 for short, 8 for bytes) Due to the division of integer MAX_ All bits except the high bit of value are set to 1, so the short value and byte value are set to all bits, corresponding to - 1 in the signed binary complement

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>