# java浮点数转二进制,Java的：浮点转换二进制浮点小数

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?

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);

}

• 1
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
02-13 1558
08-21
04-05
03-15 371
02-19 877

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。