将 int 写入二进制缓冲区 (Android) 并使用 C++ 读取

Write int to binary buffer (Android) and read with C++

我想用 Java (Android) 在二进制文件中写入一个整数,然后用 C++ 代码读取它。 我在 Java 中的代码是:

byte [] mybuffer = ByteBuffer.allocateDirect(4).putInt(1000).array;
out.write(mybuffer, 0, 4); // out is FileOutputStream

C++中的reader

std::ifstream fileToRead;
fileToRead.open("myFile", std::ios::binary);
if (!fileToRead.is_open()){
    std::cout << "[ERROR] Can't open file" << std::endl;
    exit(-1);
}
int  * myInt = new int;
fileToRead.read((char*)&myInt[0], 4);
std::cout << " The integer is " << myInt[0] <<  std::endl;

但我得到的值没有意义。

谢谢

输出Java:

buffer[0] = 0
buffer[1] = 0
buffer[2] = 3
buffer[3] = -24

输出 c++:

The integer is -402456576

您可能会遇到字节顺序问题:

#include <cstdint>
#include <fstream>
#include <iostream>
// For ntohl with Linux (Windows has similar):
#include <arpa/inet.h>

int main()
{
    // You can use the constructor to open the file:
    std::ifstream fileToRead("myFile", std::ios::binary);
    // Just check the general state of the stream:
    if(!fileToRead){
        std::cout << "[ERROR] Can't open file" << std::endl;
        // Please do not use exit to terminate a program:
        return -1;
    }
    // No need to allocate an integer. Also be specific about the size:
    int32_t myInt;
    // There might be byte order issues, here (Java is big-endian):
    fileToRead.read((char*)&myInt, sizeof(int32_t));
    // To fix it convert the integer from network byte order to host byte order:
    myInt = ntohl(myInt);
    std::cout << " The integer is " << myInt <<  std::endl;
}

为了良好的顺序,java 默认使用 BIG_ENDIAN 字节顺序:

byte[] mybuffer = ByteBuffer.allocateDirect(4)
                  .order(Order.LITTLE_ENDIAN).putInt(1000).array();

这是英特尔处理器内存架构上的顺序。