双十六进制字符串和后面

And*_*ndy 7 java string hex data-structures

在Java中将double转换为十六进制字符串相当简单.但是我该怎么做呢?我的代码在下面,我已经注意到NumberFormatException抛出的位置(大约2/3rds).

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 );

    }
}
Run Code Online (Sandbox Code Playgroud)

使用Double.valueOf失败的方式相同.

编辑:我已经在网上做了一些搜索,发现了一些非常不优雅的解决方案.例如:使用BigInteger似乎有点矫枉过正.必须有更好的方法!

pos*_*def 9

为什么不使用标准库中提供的方法: Double.valueOfDouble.toHexString

所以一个完整的往返例子就是

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);
}
Run Code Online (Sandbox Code Playgroud)

Nb Double.valueOf会给出一个盒装,DoubleDouble.parseDouble会根据需要给出一个原始double 选择.

还是我误解了什么?

  • @Andy:为了确保,你可以指定:a)`String str = Double.toHexString(-9.156013e-002)`和b)`double d = Double.valueOf(str)的输出 (2认同)

Pet*_*rey 2

您可以将字符串分成两半并解析每一半,但我认为这是最简单的。

long doubleAsLongReverse = new BigInteger(doubleAsString, 16).longValue();
Run Code Online (Sandbox Code Playgroud)

在 Java 8 中,现在有一个

long l = Long.parseUnsignedLong(doubleAsString, 16);
Run Code Online (Sandbox Code Playgroud)

并扭转这一局面

String s = Long.toUnsignedString(l, 16);
Run Code Online (Sandbox Code Playgroud)

double这些可以与将 raw 转换为longetc 的方法结合使用。