Home:ALL Converter>Cannot read integer values saved into binary file with Java

Cannot read integer values saved into binary file with Java

Ask Time:2022-05-19T06:15:41         Author:N3tMaster

Json Formatter

I implemented a procedure for saving 32bit signed integer values, retrieved from PostgreSQL, into a binary file.

I used ByteArrayOutputStream and DataOutputStream

//..


ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);

//this cycle over my retrieved recordset
while (tdb.next()) {

   out.writeInt((tdb.getInteger(1)));  //getInteger method extract integer value from recordset

}

//convert into byte array
byte[] bytes = baos.toByteArray();

//create file for output
File fileout = new File("./myfilebin.bin");
//write data
Files.write(fileout.toPath(), bytes);

//...

My input data sample contains these values:

0, 0, 42812, 42822, 41483, 0, 0, ...

When I try to read my binary file, I will get these:

0, 0, 1017577472, 1185349632, 195166208, 0, 0, ...

For reading file I wrote a simple python script:

import struct

with open("./myfilebin.bin", "rb") as f:

     for chunk in iter(lambda: f.read(4), ''):
        integer_value = struct.unpack('i', chunk)[0]
        print(integer_value)

Any idea?

Author:N3tMaster,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/72296596/cannot-read-integer-values-saved-into-binary-file-with-java
Michail Alexakis :

Probably your numbers are Big-Endian (BE) and you try to decode as Little-Endian (LE).\nTry: struct.unpack('>i', chunk) to force reading as BE.\nSee also the docs for struct module on alignment and endianess.\nFYI, DataOutputStream always writes in BE as stated in the official javadoc.",
2022-05-18T22:33:31
yy