java - `(long)(float)Long.MAX_VALUE` has the exact value, how is that possible? -


long has more bytes float, expected highest long might not stored in float. indeed case:

system.out.println(string.format("%d", long.max_value)); // 9223372036854775807 system.out.println(string.format("%.0f", (float)long.max_value)); // 9223372036854776000 

but if convert float long, how possible original value back?

system.out.println(string.format("%d", (long)(float)long.max_value)); // 9223372036854775807 

how did java somehow recover lost precision?

edit 1: info:

float j = long.max_value; system.out.println((long)j); // 9223372036854775807 

so if value stored, effect same. java ignoring 'cast' if it's stored? feel shouldn't that; changes result.

edit 2 (was wrong, undone)

the issue because result of (float)long.max_value outside range of long. when it's converted back, it's clamped maximum representable value.

from jls (emphasis mine):

a narrowing conversion of floating-point number integral type t takes 2 steps:

[...]

otherwise, 1 of following 2 cases must true:

[...]

the value must large (a positive value of large magnitude or positive infinity), , result of first step largest representable value of type int or long.

to prove it:

long x = long.max_value - 10; system.out.println(x);                // 9223372036854775797 system.out.printf("%.0f", (float)x);  // 9223372036854776000 system.out.println((long)(float)x);   // 9223372036854775807 (look familiar?) 

(thanks @t.j. crowder suggested example.)


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -