Question

I am experiencing some sort of difficulties with storing structure {int, int, long} as byte array in java and reading it as binary structure in Cpp.

I have tried nearly everything. My biggest success was when I could read Long value properly, but integers were some random numbers.

I am affraid of endianness and I am not sure how can I decide which language use little or big endianness. Can anybody, please, tell me, how can I store primitive types such as int, long, double in java and read it in Cpp?

Thank you, it would be really helpful.

EDIT: I know how do I want to read it in 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));

In Java, I've tried many ways, my last try was:

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

but Java code is open.

Was it helpful?

Solution

You wrote only the very first integer.. You never wrote the second one followed by the long.. Thus any values you read would be random of course. Just remember that sizeof(long) in C++ might not actually be 8 as it is in java! Also don't forget that the structure in C++ might be padded and it'd be better to read each value one at a time into the struct's fields.

This works..

On the java side:

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

}

and on the C++ side:

#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";
    }
}

Results are: 5 6 7.

It might even be better to do:

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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top