How do you produce a 16 bit unsigned integer and a 64-bit unsigned integer in Java? This question is related to implementing a standard. I am not in a position to change the spec.
Other perhaps relevant bits of the spec. this question is related to:
- most significant bit MUST be 0.
- must be expressed in network byte order.
Application context: The number (in either form) represents the length of data being sent. The length can be big or small. I’ve first found the length of the message to be sent as a long.
So I’m starting with: long length = getLength();
I then need to convert the long variable “length” to either of the two above, depending on how big it is. In the end, I’m pretty sure I’ll need to do a .getBytes() when I send the length. The recipient will interpret as described above.
If the most significant bit must be zero, then the number is the same whether it is signed or unsigned (assuming a two’s complement representation). So for instance, 16 bit integers with the MSB zero represent the numbers from
0to32767inclusive.Assuming that you are writing to an
OutputStreamand that your definition of “network order” is most significant byte first, then you need to do something like this:and
Note that these works for signed and unsigned integers. (Or to be more precise for the Java context, they work if the argument represents a signed or unsigned integer.)