簡體   English   中英

存儲Cpp中可讀的Java字節數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM