It's fairly simple to convert a double to a hexadecimal string in Java. But how do I do the reverse? My code is below and I've noted where a NumberFormatException
is thrown (about 2/3rds down).
public class HexToDoubleTest {
public static void main( String args[] ) {
// This is the starting double value
double doubleInput = -9.156013e-002;
// Convert the starting value to the equivalent value in a long
long doubleAsLong = Double.doubleToRawLongBits( doubleInput );
// Convert the long to a String
String doubleAsString = Long.toHexString( doubleAsLong );
// Print the String
System.out.println( doubleAsString );
// Attempt to parse the string back as a long
// !!! This fails with a NumberFormatException !!!
long doubleAsLongReverse = Long.parseLong( doubleAsString, 16 );
// Convert the long back into the original double
double doubleOutput = Double.longBitsToDouble( doubleAsLongReverse );
// Confirm that the values match
assert( doubleInput == doubleOutput );
}
}
Using Double.valueOf
fails in the same manner.
Edit: I've done a few searches on the web already and found some very inelegant solutions. For example: Using a BigInteger
seems like overkill. There's got to be a better way!
Why not use the methods provided in standard library: Double.valueOf and Double.toHexString
So a full round trip example would be
public static void main(String[] args){
double doubleValue = -0.03454568;
System.out.println("Initial double value is " + doubleValue);
String hexStringRepresentation = Double.toHexString(doubleValue);
System.out.println("Hex value is " + hexStringRepresentation);
double roundtrippedDoubleValue = Double.valueOf(hexStringRepresentation);
System.out.println("Round tripped double value is " + roundtrippedDoubleValue);
}
Nb Double.valueOf
will give a boxed Double
and Double.parseDouble
will give a primitive double
choose as appropriate.
or am I misunderstanding something?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With