如何读取C / Matlab的用JAVA创建的二进制文件 [英] How to read binary file created by C/Matlab using JAVA
问题描述
我已经尝试使用下面的MATLAB code创建一个二进制文件:
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");
fwrite(fid, n, 'int32');
fwrite(fid, x, 'int32');
fclose(fid);
我可以使用下面的C code阅读本文件:
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;
}
......
以上C code能读取正确的结果。不过,我现在想读在JAVA这样的二进制文件。我的code如下所示:
The above C code can read correct results. However, I now want to read such binary file in JAVA. My code is shown 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();
它并终止N + 1圈之后,但结果是不正确的。任何人都可以帮助我。非常感谢!
It DOES terminates after n+1 loops, but the results are not correct. Can anybody help me out. Thanks very much!
推荐答案
正如我猜测它是一个字节序的问题,即
您的二进制文件被写成小尾数整数
(可能是因为你使用的是Intel或类似的CPU)。
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).
在Java code,然而,在读大端整数,无论它运行在什么CPU。
The Java code, however, is reading big-endian integers, no matter what CPU it is running on.
要显示的问题,下面code前后端序转换后会读取数据并显示该整数作为十六进制数。
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
这篇关于如何读取C / Matlab的用JAVA创建的二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!