, , javadoc Long.toHexString() : " 16. 2 ^ 64, , ." parseLong : " long ..."
So, if you have negative input, then 2 ^ 64 throws a NumberFormatException.
If the input is changed to
double doubleInput = 9.156013e-002;
the conversion works correctly without exception. To deal with negative input, a little extra processing is required.
Here is a class that shows one way to do the conversion without using BigInteger buffers or bytes:
public class Temp {
public String getDoubleAsHexString(double input) {
long doubleAsLong = Double.doubleToRawLongBits(input);
return Long.toHexString(doubleAsLong);
}
public double convertHexStrToDouble(String input) {
String s2 = preprocess(input);
boolean negative = true;
if (input.equalsIgnoreCase(s2))
negative = false;
long doubleAsLongReverse = Long.parseLong(s2, 16);
double doubleOutput = Double.longBitsToDouble(doubleAsLongReverse);
if (negative)
return -doubleOutput;
return doubleOutput;
}
private String preprocess(String doubleAsHexString) {
String s0 = doubleAsHexString.substring(0, 1);
int int1 = Integer.parseInt(s0, 16);
if (int1 < 8)
return doubleAsHexString;
int1 = int1 - 8;
s0 = Integer.toString(int1);
if (int1 == 0)
s0 = "";
return s0 + doubleAsHexString.substring(1);
}
}
And here is the junit test class:
public class TempTest {
private Temp t;
@Before
public void setUp() throws Exception {
t = new Temp();
}
@Test
public void testConvertHexStrToNegativeDouble() {
double doubleInput = -9.156013e-002;
String hexStr = t.getDoubleAsHexString(doubleInput);
double doubleOutput = t.convertHexStrToDouble(hexStr);
assertEquals(doubleInput, doubleOutput, 0.0);
}
@Test
public void testConvertHexStrToPositiveDouble() {
double doubleInput = 9.156013e-002;
String hexStr = t.getDoubleAsHexString(doubleInput);
double doubleOutput = t.convertHexStrToDouble(hexStr);
assertEquals(doubleInput, doubleOutput, 0.0);
}
}
source
share