将int写入二进制缓冲区(Android)并使用C ++读取 [英] Write int to binary buffer (Android) and read with C++
本文介绍了将int写入二进制缓冲区(Android)并使用C ++读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用Java(Android)在二进制文件中写一个整数,然后用C ++代码读取它. 我在Java中的代码是:
I want to write an integer in a binary file with Java (Android) and then read it with a C++ code. My code in Java is:
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;
但是我得到了没有意义的价值.
But I get values which doesnt make sense.
谢谢
输出Java:
buffer[0] = 0
buffer[1] = 0
buffer[2] = 3
buffer[3] = -24
输出c ++:
The integer is -402456576
推荐答案
您可能会遇到字节顺序问题:
You may encounter a byte-order problem:
#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;
}
这篇关于将int写入二进制缓冲区(Android)并使用C ++读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文