Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double to Hex String and Back

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!

like image 658
Andy Avatar asked Mar 25 '11 14:03

Andy


1 Answers

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?

like image 129
posdef Avatar answered Nov 02 '22 06:11

posdef