H. Saoud
H. Saoud

Reputation: 63

Java ByteBuffer BigEndian Double

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

Upvotes: 6

Views: 541

Answers (1)

VGR
VGR

Reputation: 44414

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.

Upvotes: 2

Related Questions