简体   繁体   中英

Send uint32_t from C++ to Java

I am currently writing a server in C++ and an Android app that revceives data from it using google protobuf. Currently I frame the data with the size, so basically I send

-----------------------------------------------------
| payload size (4byte, unsigned) | protobuf payload |
-----------------------------------------------------

I have no problem deserializing the stuff in Java, but how can I convert the bytes from the socket to an unsigned integer? The payload size is always a uint32_t that has been converted with htonl to network byte order. So Java needs to convert to host byte order and convert it to an Integer.

Okay, so, in Java, ints are always 32 bits, so you just need to read those four bytes and turn that into an int using ByteBuffer . You might think we'd need to specify a byte order, but it turns out that ByteBuffers reads bytes in big endian order by default, so that already works for the network order:

byte[] bytes = ...;
int size = ByteBuffer.wrap(bytes).getInt();

However, since all integers in Java are signed, then size above might end up negative if it's too big. You probably don't want that. You could cast it to long, but if the int is negative its sign will be extended, and you'll end up with a negative long.

The solution is to interpret it as a long, which, even though it is signed, is 64 bits and therefore big enough to represent a 32 bit unsigned integer. Thankfully, there's a method in Java 8 that does just that:

long actualSize = Integer.toUnsignedLong(size);

There you go, now you can play with the size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM