在
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 );
}
}
使用Double.valueOf以相同的方式失败.
编辑:我已经在网上做了一些搜索,发现了一些非常不优雅的解决方案.例如:使用BigInteger似乎有点矫枉过正.必须有更好的方法!