gpt4 book ai didi

Java:将浮点二进制转换为浮点十进制

转载 作者:行者123 更新时间:2023-11-30 09:08:50 25 4
gpt4 key购买 nike

我想转换表示 IEEE754 double 的尾数部分的字符串。找不到Java中有没有这样的转换方法,以避免手动添加1 + 1/2 + 1/4 + 1/8等。

|010000001100101000011111000000000000000000000000000000000000000 --> IEEE754 中的 13374|------------1010000111110000000000000000000000000000000000000000 --> 尾数部分| 1.1010000111110000000000000000000000000000000000000000 --> 恢复固定值 1

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

最佳答案

是的,有多种方法可以读取二进制表示。但是您没有 IEEE 格式的表示。

我会忽略句点并读取为 BigInteger base2,然后创建一个值来除以也使用 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);
}

关于Java:将浮点二进制转换为浮点十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23325504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com