开发者

problem when Java and C++ talk with each other

开发者 https://www.devze.com 2023-02-18 16:13 出处:网络
I have a program in C++ and it writes a binary file on disk. Then I use a Java program to read t开发者_运维问答he number. The problem is the number read is different from the number written.

I have a program in C++ and it writes a binary file on disk. Then I use a Java program to read t开发者_运维问答he 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?


Java's java.nio buffers let you specify the endianness.

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.

To read a file using a ByteBuffer do something like:

ByteBuffer buffer = new RandomAccessFile(myFile, "r")
    .getChannel.map(MapMode.READ, offset, length);

Remember to close it when you're done.

0

精彩评论

暂无评论...
验证码 换一张
取 消