How to read binary created by C / Matlab using JAVA

I created a binary using the following matlab code:

x is an array of int32 numbers n is the length of x fid = fopen("binary_file.dat", "wb"); fwrite(fid, n, 'int32'); fwrite(fid, x, 'int32'); fclose(fid); 

I can use the following C code to read this file:

 fp = fopen("binary_file.dat", "rb"); int n; fread(&n, 4, 1, fp);//read 4 bytes int *x = new int[n]; for (int i = 0; i < n; i++) { int t; fread(&t,4, 1,fp);//read 4 bytes x[i] = t; } ...... 

The above C code can read the correct results. However, now I want to read such a binary in JAVA. My code is displayed as follows:

 DataInputStream data_in = new DataInputStream( new BufferedInputStream( new FileInputStream( new File("binary_file.dat")))); while(true) { try { int t = data_in.readInt();//read 4 bytes System.out.println(t); } catch (EOFException eof) { break; } } data_in.close(); 

It ends after n + 1 cycles, but the results are incorrect. Can someone help me. Many thanks!

+4
java c binary matlab
source share
1 answer

As I already guessed, this is a question about content, i.e. your binary is written as low-value integers (perhaps because you are using Intel or a similar processor).

However, Java code reads integers other than numbers, regardless of which processor it runs on.

To show the problem, the following code will read your data and display the integers as a hexadecimal number before and after the endianness conversion.

 import java.io.*; class TestBinaryFileReading { static public void main(String[] args) throws IOException { DataInputStream data_in = new DataInputStream( new BufferedInputStream( new FileInputStream(new File("binary_file.dat")))); while(true) { try { int t = data_in.readInt();//read 4 bytes System.out.printf("%08X ",t); // change endianness "manually": t = (0x000000ff & (t>>24)) | (0x0000ff00 & (t>> 8)) | (0x00ff0000 & (t<< 8)) | (0xff000000 & (t<<24)); System.out.printf("%08X",t); System.out.println(); } catch (java.io.EOFException eof) { break; } } data_in.close(); } } 

If you do not want to make manual changes to the index, see the answers to this Question:
convert small Endian file to large Endian

+4
source share

All Articles