Hey Guys, I have a program in C++ and it writes a binary file on disk. Then I use a Java program to read the number. The problem is the number read is different from the number written... Say, I write an integer 4 using c++ and get back 67108864 when use JAVA to read it ( using readint() ) ... I suspect its due to big or small endian. Do you have any simple solutions to solve this?
嘿伙计们,我有一个C ++程序,它在磁盘上写了一个二进制文件。然后我使用Java程序读取数字。问题是读取的数字与写入的数字不同...说,我使用c ++写一个整数4并在使用JAVA读取它时返回67108864(使用readint())...我怀疑它是由于大或小端。你有什么简单的解决方案来解决这个问题吗?
Thanks a lot!!!
非常感谢!!!
1 个解决方案
#1
3
Java's java.nio
buffers let you specify the endianness.
Java的java.nio缓冲区允许您指定字节顺序。
See http://download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html especially the order
method which lets you specify endianness and the getInt
method which lets you read an int.
请参阅http://download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html,特别是允许您指定字节顺序的order方法和允许您读取int的getInt方法。
To read a file using a ByteBuffer
do something like:
要使用ByteBuffer读取文件,请执行以下操作:
ByteBuffer buffer = new RandomAccessFile(myFile, "r")
.getChannel.map(MapMode.READ, offset, length);
Remember to close it when you're done.
记得在完成后关闭它。
#1
3
Java's java.nio
buffers let you specify the endianness.
Java的java.nio缓冲区允许您指定字节顺序。
See http://download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html especially the order
method which lets you specify endianness and the getInt
method which lets you read an int.
请参阅http://download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html,特别是允许您指定字节顺序的order方法和允许您读取int的getInt方法。
To read a file using a ByteBuffer
do something like:
要使用ByteBuffer读取文件,请执行以下操作:
ByteBuffer buffer = new RandomAccessFile(myFile, "r")
.getChannel.map(MapMode.READ, offset, length);
Remember to close it when you're done.
记得在完成后关闭它。