Reputation: 111
I am trying to implement a binary protocol in a Java Android application. The variables in this protocol are unsigned and are either uint32, uint16 or uint8.
I am having trouble with sending integer values. For example, when I try to send a short with a value of 1, the server (written in C++) receives a value of 256.
After searching a bit, I saw some posts talking about endianess and all but it doesn't really give me an answer.
How can I manage to get the bits stored in my variables in Java aligned in the same fashion as the one in C++.
Thanks
Upvotes: 0
Views: 357
Reputation: 111
I solved it! It was a problem of endianess. I solved it using the order() method of ByteBuffer.
Upvotes: 0
Reputation: 111289
C++ does not define the order in which bytes in multibyte integers are stored. You should pick one standard and make sure that everyone uses it.
The standard API in Java has many classes that use big-endian byte order, so you might as well use that as the standard. To receive these correctly in C++ you can use the ntohl
and ntohs
functions for the conversion, for example.
Upvotes: 1