How to read binary file created by C/Matlab using JAVA

前端 未结 1 665
感动是毒
感动是毒 2020-12-19 15:59

I have created a binary file using the following matlab code:

x is an array of int32 numbers
n is the length of x

fid = fopen(\"binary_file.dat\", \"wb\");
         


        
相关标签:
1条回答
  • 2020-12-19 16:51

    As I was guessing it is an endianness issue, i.e. your binary file is written as little-endian integers (probably, because you are using a Intel or similar CPU).

    The Java code, however, is reading big-endian integers, no matter what CPU it is running on.

    To show the problem the following code will read your data and display the integers as hex number before and after 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 don't want to do change endianness "manually", see answers to this question:
    convert little Endian file into big Endian

    0 讨论(0)
提交回复
热议问题