Java: convert floating point binary to floating po

2019-07-20 10:00发布

问题:

I want to convert a string representing the mantissa portion of a IEEE754 double. Cannot find if there is such a conversion method in Java, in order to avoid manually adding 1 + 1/2 + 1/4 + 1/8 etc.

|0100000011001010000111110000000000000000000000000000000000000000 --> 13374 in IEEE754 |------------1010000111110000000000000000000000000000000000000000 --> mantissa part | 1.1010000111110000000000000000000000000000000000000000 --> restoring fixed value 1

String s = "1.1010000111110000000000000000000000000000000000000000"
double mant10 = Double.readFromFloatBinary(s); // does such method exists in Java?

回答1:

Yes, there are ways to read from a binary representation. But you don't have a representation in an IEEE format.

I would ignore the period and read as a BigInteger base2, then create a value to divide by also using BigInteger:

private static double binaryStringToDouble(String s) {
    return stringToDouble(s, 2);
}

private static double stringToDouble(String s, int base) {
    String withoutPeriod = s.replace(".", "");
    double value = new BigInteger(withoutPeriod, base).doubleValue();
    String binaryDivisor = "1" + s.split("\\.")[1].replace("1", "0");
    double divisor = new BigInteger(binaryDivisor, base).doubleValue();
    return value / divisor;
}

@Test
public void test_one_point_5() {
    String s = "1.1";
    double d = binaryStringToDouble(s);
    assertEquals(1.5, d, 0.0001);
}

@Test
public void test_6_8125() {
    String s = "110.1101";
    double d = binaryStringToDouble(s);
    assertEquals(6.8125, d, 0.0001);
}

@Test
public void test_yours() {
    String s = "1.1010000111110000000000000000000000000000000000000000";
    double d = binaryStringToDouble(s);
    assertEquals(1.632568359375, d, 0.000000000000000001);
}

@Test
public void test_yours_no_trailing_zeros() {
    String s = "1.101000011111";
    double d = binaryStringToDouble(s);
    assertEquals(1.632568359375, d, 0.000000000000000001);
}