Java htonl implementation

I communicate with the server, each message sent to the server must be supplemented by the length of the message,

unsigned int len = htonl(msg.size()); 

In C, executing the length via htonl and filling the message works, in byte order Java AFAIK is already in network order, so I assumed that all I need to do is write the length of the line before the message to the stream, but this does not work, I missed something?

 stream.write(msg.length()); stream.write(msg.getBytes()); 

A stream is an OutputStream .

+4
source share
4 answers

The problem with your implementation is that the write method writes only one byte, see the documentation. An important suggestion here is: "24 high-order bits of b are ignored." Therefore, stream.write(msg.length()); probably doesn't do what is intended. (I assume msg.length () returns an int, correct me if I am wrong here.)

Try writing four bytes of int:

 stream.write(msg.length() % 256); stream.write((msg.length() / 256) % 256); stream.write((msg.length() / (256 * 256)) % 256); stream.write((msg.length() / (256 * 256 * 256)) % 256); 

This writes the low byte first, you can reorder if you want. You can do the conversion to bytes also with a bit shift, the division looks more clear to me, but this is a matter of personal taste.

+1
source
 int htonl(int value) { return ByteBuffer.allocate(4).putInt(value) .order(ByteOrder.nativeOrder()).getInt(0); } 

As an alternative

 int htonl(int value) { if (ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN) { return value; } return Integer.reverseBytes(value); } 
+10
source

Take a look at the Int.reverseBytes () method, which on platforms like x86 will fall into the x86 bswapl opcode.

You can set this from the result of System.getProperty ("sun.cpu.endian")

+1
source

And int does not have a given byte order at run time on the Java platform, simply because there is no way to directly observe a bitmap representing any value. However, methods that somehow convert int values ​​(or others) to byte[] have a specific conversion.

Thus, the correct transmission / reception of this value depends on the correct encoding / decoding with / from byte[] . Unless you tell us how you are doing this step, we cannot help you do it right.

0
source

Source: https://habr.com/ru/post/1307459/


All Articles