【问题标题】:Java ByteBuffer BigEndian DoubleJava ByteBuffer BigEndian Double
【发布时间】:2017-05-22 14:14:50
【问题描述】:

当我尝试在文件中写入具有如下值的二进制文件时:

public static main(String[] args){
    ByteBuffer output = ByteBuffer.allocate(80);
    output.order(ByteOrder.BIG_ENDIAN);
    output.putDouble(545.5);
    appendByteArrayInFile("c:/myPath/", "test.bin", output.array());
}
    private static void appendByteArrayInFile(String exportDirectory, String fileName, byte[] toAppendInFile) {
    if (toAppendInFile != null) {
        File targetExport = createPathAndFile(exportDirectory + fileName);
        try (FileOutputStream output = new FileOutputStream(targetExport, true)) {
            output.write(toAppendInFile);
        } catch (Exception e) {
            // no
        }
    }
}
private static File createPathAndFile(String path) {
    File targetExport = new File(path);
    targetExport.getParentFile().mkdirs();
    return targetExport;
}

问题是,当我查看生成的文件时,似乎 double 以 little-endian 样式放置,而当我将 ByteOrder 切换为 little-endian 时,double 以 big-endian 写入... 但是当我输入一个 int 时,字节序是正确的。

BigEndian 中的双精度输出:

01000000 10000001 00001100 00000000 00000000 00000000 00000000 00000000

littleEndian 中的双精度输出:

00000000 00000000 00000000 00000000 00000000 00001100 10000001 01000000

在 bigEndian 中使用 int 输出:

00000000 00000000 00000010 00100001

【问题讨论】:

    标签: java endianness bytebuffer


    【解决方案1】:

    据我了解,IEEE 浮点数中的有效数字根本不是“字节序”,因为它不是一个独立的数值。如果有效数字表示为以 2 为底的数字,则它是一个二进制数字序列,将跟随小数点。 (小数点左侧总是假定为“1.”。)有效数字表示为0001 00001100 00000000 00000000 00000000 00000000 00000000,这意味着实际有效数字是1.00010000110…2。则实际值为 1.00010000112 × 29,即 545.5。

    【讨论】:

    • 如果浮点数没有字节序,那为什么小字节序和大字节序有区别?
    • 实际上,我刚刚注意到您的代码包含buffer.order(ByteOrder.BIG_ENDIAN); ......这意味着它正在设置不同 ByteBuffer(而不是output)的字节顺序。
    • 复制我的代码时出错,我的坏t实际上是output.order(ByteOrder.BIG_ENDIAN);
    • 在 little-endian ByteBuffer 上执行 putDouble 只会反转字节,如您所见。我的回答的重点是您打印的第一个值是正确的,实际上是大端;这些位按照它们在基数 2 有效数中出现的顺序表示十进制数字。
    猜你喜欢
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    相关资源
    最近更新 更多