Home > Blockchain >  Get a double from a long created from Double.toLongBits
Get a double from a long created from Double.toLongBits

Time:10-30

Is there a way to reverse a long I got from Double.toLongBits back to a Double?
The following does not work:

Double n = 171.30672219;
System.out.println(Double.doubleToLongBits(n));
System.out.println(new Double(Double.doubleToLongBits(n)));  

this prints:

4640231336019091517
4.6402313360190915E18

While I wanted to get back the 171.30672219

CodePudding user response:

As the documentation for doubleToLongBits says:

In all cases, the result is a long integer that, when given to the longBitsToDouble(long) method, will produce a floating-point value the same as the argument to doubleToLongBits (except all NaN values are collapsed to a single "canonical" NaN value).

double n = 171.30672219;
System.out.println(Double.doubleToLongBits(n));
System.out.println(Double.longBitsToDouble(Double.doubleToLongBits(n)));

CodePudding user response:

You can do it like this.

Double n = 171.30672219;
long bits = Double.doubleToLongBits(n);
double d = Double.longBitsToDouble(bits);
System.out.println(d);

prints

171.30672219

Welcome to the world of IEEE 754.

  • Related