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

时间:2015-08-07 12:48:11

标签: java android c++ binary bin

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

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

C ++中的读者

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

2 个答案:

答案 0 :(得分:4)

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

#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;
}

答案 1 :(得分:1)

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

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

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