2

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?
mins
  • 6,478
  • 12
  • 56
  • 75
  • 4
    `.` (dot) doesn't come in binary. `s` is not a binary number. – Braj Apr 27 '14 at 15:55
  • 2
    Maybe not in Java, but in ordinary maths it does, e.g. 1.1(2) is 1.5(10). Try http://www.exploringbinary.com/binary-converter/ to confirm. – mins Apr 27 '14 at 16:00
  • Do you want to convert a float to binary first and then binary to double decimal? – Braj Apr 27 '14 at 16:04
  • 1
    Read [Java: How to convert a String of Binary values to a Float and vice-versa?](http://stackoverflow.com/questions/5157664/java-how-to-convert-a-string-of-binary-values-to-a-float-and-vice-versa) – Braj Apr 27 '14 at 16:05
  • What will be value of math10 as per your question? – Braj Apr 27 '14 at 16:07
  • The link is for float, there is no similar methods for double. That's the problem. In my case mant10 = 1.632568359375. That's 1 + 1/2 + 1/8 etc. – mins Apr 27 '14 at 16:14

1 Answers1

2

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);
}
weston
  • 54,145
  • 21
  • 145
  • 203