存储Cpp中可读的java字节数组

Storing java byte array readable in Cpp

本文关键字:java 字节 字节数 数组 Cpp 存储      更新时间:2023-10-16

我在java中将结构{int,int,long}存储为字节数组,并在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++中的结构可能是填充的,最好一次将每个值读取到结构的字段中。

这很管用。。

在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));