Java ByteBuffer BigEndian Double
Asked Answered
S

1

6

When I try to write in a file a binary files with value like this :

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

The thing is that when I look at the file generated, it seems that the double is putted in little endian style, and when I switch ByteOrder to little-endian, the double is written in big-endian ... But when I put an int, the endianness is correct.

Output with double in BigEndian :

01000000 10000001 00001100 00000000 00000000 00000000 00000000 00000000

Output with double in littleEndian :

00000000 00000000 00000000 00000000 00000000 00001100 10000001 01000000

Output with int in bigEndian:

00000000 00000000 00000010 00100001
Spinode answered 22/5, 2017 at 14:14 Comment(0)
C
2

As I understand it, the significand in an IEEE floating-point number is not “endian” at all, because it’s not a standalone numeric value. It’s a sequence of binary digits that would follow the decimal point if the significand were expressed as a base 2 number. (To the left of the decimal point, “1.” is always assumed.) The significand is represented as 0001 00001100 00000000 00000000 00000000 00000000 00000000, which means the actual significand is 1.00010000110…2. The actual value, then, is 1.00010000112 × 29, which is 545.5.

Collage answered 22/5, 2017 at 15:34 Comment(4)
If there is no endianness in a floating-point number, then why is there differences between little and big endian writings?Spinode
Actually, I just noticed that your code contains buffer.order(ByteOrder.BIG_ENDIAN); … meaning it is setting the byte order of a different ByteBuffer (not output).Collage
It's a mistake during copying my code, my bad t is actually output.order(ByteOrder.BIG_ENDIAN);Spinode
Executing putDouble on a little-endian ByteBuffer just reverses the bytes, as you are seeing. The point of my answer is that the first value you printed is correct and is in fact big-endian; the bits represent the decimal digits in the order they would occur in the base 2 significand.Collage

© 2022 - 2024 — McMap. All rights reserved.