【发布时间】:2011-07-22 23:20:24
【问题描述】:
在 Java 中将 double 转换为十六进制字符串相当简单。但是我该如何做相反的事情呢?我的代码在下面,我已经注意到 NumberFormatException 被抛出的位置(大约下降了 2/3)。
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 似乎有点矫枉过正。一定有更好的方法!
【问题讨论】:
标签: java string data-structures hex