繁体   English   中英

使用 java 中的给定浮点格式将十六进制转换为双精度

[英]Convert hex to double with a given floating-point format in java

我有一个字符串表示 64 位 integer“0000000000EA6484”的十六进制值。 我需要使用 Java 将其转换为双精度值“0.9155962467”。 我得到的指令是格式化 int64_t(8 字节)类型的 12.52 FP 值。

我通过谷歌搜索发现 C++ 中的int64_t数据类型是签名的 integer。 我还发现这篇文章似乎很相关,但让我有点困惑。

最后,我尝试了以下 java 代码,看看我是否得到了预期的结果,但在这两种情况下我都得到了“7.5894195E-317”。 我确信要么我不明白如何解决这个问题,所以我希望能得到一些帮助,或者预期的 output 是错误的。

import java.nio.ByteBuffer;
public class Main {
public static void main(String[] args) {
String hexString = "0000000000EA6484";//0.9155962467

    long longValue = Long.parseLong(hexString, 16);
    longValue = Long.parseUnsignedLong(hexString, 16);
    System.out.println(longValue);

    double doubleValue = Double.longBitsToDouble(longValue);
    System.out.println(doubleValue);

    byte[] bytes = hexStringToByteArray(hexString);
    doubleValue = ByteBuffer.wrap(bytes).getDouble();
    System.out.println(doubleValue);
}
public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
    }
    return data;
}
}

如图所示, 0000000000EA6484表示 Q40.24 格式的 0.9155962467193603515625,而不是浮点格式。 这是一种定点格式,有 40 个 integer 位(包括一个符号位)和 24 个小数位。 To convert it from the integer represented by those bits in a 64-bit integer format to the value represented by the same bits in the Q12.52 format, divide it by 2 24 : EA6484 16 = 15361156 10 , 15361156 / 2 24 = 0.9155962467193603515625 . 在 Java 中,将 integer 值除以 16777216 (2 24 ) 就足够了。

看来谁告诉你这是 12.52 FP 格式是错误的。 即使存在一些字节序问题或任何其他字节重新排序,也无法解释相对于 12.52 格式的位的移位 position,因为它的不同之处在于子字节分数(52 位 - 24 位 = 28 位,这是 3½ 字节)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM