Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 610
H. Saoud Avatar asked May 22 '17 14:05

H. Saoud


1 Answers

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.

like image 59
VGR Avatar answered Oct 27 '22 05:10

VGR