【发布时间】: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变量,地址运算符&就足够了:int myInt; fileToRead.read(reinterpret_cast<char*>(&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