【问题标题】:Write int to binary buffer (Android) and read with C++将 int 写入二进制缓冲区(Android)并使用 C++ 读取
【发布时间】:2023-12-07 11:23:01
【问题描述】:

我想用 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

【问题讨论】:

  • 您应该将奇怪的输出添加到您的问题中:)(您的问题中也没有实际的“问题”)
  • C++ 代码的实际阅读部分看起来是合法的,但它确实具有 Java 编码器的感觉。无需动态分配myInt 变量,地址运算符&amp; 就足够了:int myInt; fileToRead.read(reinterpret_cast&lt;char*&gt;(&amp;myInt), sizeof(myInt));
  • 查看示例输入和输出会很有用,尤其是逐字节打印。
  • 在 Android 部分我得到:mybuffer[0] = 0 mybuffer[1] = 0 mybuffer[2] = 3 mybuffer[3] = -24 在 C++ 部分:myInt = -402456576我也删除了新的 int

标签: java android c++ binary bin


【解决方案1】:

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

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

【讨论】:

  • 是的,谢谢!这种方法也适用于大量浮点数吗?谢谢
【解决方案2】:

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

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

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

【讨论】: