Search code examples
javaandroidc++read-writegoogle-project-tango

Binary writing from Android-Java reading wrong from UE4-C++


I am writing a binary reader that needs to read in a very specific set of binary written by an Android Tablet. I have run into several issues reading this binary, the first and foremost being that it does not resemble the data I wrote in the first place. I have read a little bit about endianness, words, and how they are made on different systems and I am curious as to if this could be the root of the problem. Any information would be good at this point, but the specific thing I would like to know is: Considering the lines below, why is the binary not being read in as the same value as it is written out as? How can I fix this?

Say numPoints = 5000.

(OUT FUNCTION - Android-java)
out.writeInt(numPoints);
(IN FUNCTION - UE4-c++)
reader << numPoints;

numPoints now equals some really really large number that I can't explain.

I am using Windows 8.1 x64 and a Google-Project-Tango Tablet.


Solution

  • Your C++ code is probably reading numbers in little-endian. Java (at least DataOutputStream) writes binary numbers as big-endian.

    It's probably simpler to fix this on the Java side since there's a built-in function for it:

    out.writeInt(Integer.reverseBytes(numPoints));
    

    You should also check whether UE4 guarantees that binary files are little-endian, or whether it's the machine's native endianness - otherwise there's a chance that you might want to port your game to a big-endian platform and run into problems later.