[英]Storing java byte array readable in Cpp
我在将结构{int,int,long}存储为java中的字节数组并在Cpp中将其读取为二进制结构时遇到了一些困难。
我已经尝试了几乎所有东西。 我最大的成功是可以正确读取Long值,但整数是一些随机数。
我很喜欢字节序,我不确定如何决定哪种语言使用的字节序少或大。 谁能告诉我,如何在Java中存储诸如int,long,double之类的原始类型并在Cpp中读取它?
谢谢,这真的很有帮助。
编辑:我知道我想如何在C ++中阅读它:
struct tick {
int x;
int y;
long time;
};
...
tick helpStruct;
input.open("test_file", ios_base::in | ios_base::binary);
input.read((char*) &helpStruct, sizeof(tick));
在Java中,我尝试了很多方法,最后一次尝试是:
DataOutput stream = new DataOutputStream(new FileOutputStream(new File("test_file")));
byte[] bytes = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(1).array();
for (byte b : bytes) {
stream.write(b);
}
但是Java代码是开放的。
您只写了第一个整数。您从未写过第二个整数,后跟长整数。因此,您读取的任何值当然都是随机的。 只需记住,C ++中的sizeof(long)
可能实际上不像Java中那样为8! 同样不要忘记,C ++中的结构可能会被填充,最好一次将每个值读入struct的字段中。
这有效..
在Java方面:
package test;
import java.io.*;
import java.nio.*;
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
DataOutput stream = new DataOutputStream(new FileOutputStream(new File("C:/Users/Brandon/Desktop/test_file.dat")));
int sizeofint = 4;
int sizeoflong = 4;
ByteBuffer buffer = ByteBuffer.allocate(sizeofint + sizeofint + sizeoflong).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(5).putInt(6).putInt(7);
byte[] bytes = buffer.array();
for (byte b : bytes) {
stream.write(b);
}
}
}
在C ++方面:
#include <fstream>
#include <iostream>
struct tick
{
int x;
int y;
long time;
};
int main()
{
std::fstream file("C:/Users/Brandon/Desktop/test_file.dat", std::ios::in | std::ios::binary);
if (file.is_open())
{
tick t = {0};
file.read(reinterpret_cast<char*>(&t), sizeof(t));
file.close();
std::cout<<t.x<<" "<<t.y<<" "<<t.time<<"\n";
}
}
结果是: 5 6 7
。
这样做可能更好:
file.read(reinterpret_cast<char*>(&t.x), sizeof(t.x));
file.read(reinterpret_cast<char*>(&t.y), sizeof(t.y));
file.read(reinterpret_cast<char*>(&t.time), sizeof(t.time));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.