2011-10-12 5 views
4

를 사용하여 C/matlab에 의해 생성 된 바이너리 파일을 읽는 방법 :나는 다음과 같은 MATLAB 코드를 사용하여 바이너리 파일을 만든 JAVA

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; 
} 
...... 
:

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); 

내가이 파일을 읽기 위해 다음과 같은 C 코드를 사용할 수 있습니다

위의 C 코드는 올바른 결과를 읽을 수 있습니다. 그러나 이제 JAVA에서 이진 파일을 읽고 싶습니다. 내 코드는 다음과 같이 표시됩니다.

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(); 

n + 1 루프 이후에 종료되지만 결과가 올바르지 않습니다. 아무도 나를 도와 줄 수 없어요. 매우 감사합니다!

+1

어떻게 결과가 정확하지 않습니다? 예를 들어'System.out.println (...) '에 주어진'n'의 값은 무엇입니까? –

+4

단지 첫 번째 추측입니다. 어쩌면 엔디안 문제 일 수도 있습니다. – Curd

+0

@ Curd 's line도 함께 생각하고있었습니다. 이미 다른 사람들에게 유용 할 수 있기 때문에 답을 직접 풀어 본다면 답을 자유롭게 게시 할 수 있습니다. –

답변

4

내 생각에 귀찮은 문제는 입니다. 이진 파일은 리틀 엔디안 정수 (인텔 또는 이와 비슷한 CPU를 사용하고 있기 때문에)로 작성되었습니다.

그러나 Java 코드는 실행중인 CPU에 관계없이 빅 엔디안 정수를 읽습니다.

문제를 표시하려면 다음 코드는 데이터를 읽고 endianness 변환 전후의 16 진수로 정수를 표시합니다.

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(); 
    } 
} 

당신이 "수동으로"변화 엔디 언을이 질문에 대한 답변을보고 싶지 않으면 :
convert little Endian file into big Endian

관련 문제