Decode an unsigned two-byte count in Java
Network data often stores unsigned quantities. Set the buffer byte order explicitly and widen the signed short before displaying the count.
A simple example
Read most significant byte first
- Start with Bytes 00 and 02 in hexadecimal
- Do this Read most significant byte first
- Result 2
Apply it to a real problem
- Start with Packet header FF FE
- Do this Read its unsigned count
- Result 65,534
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
import java.nio.*;
public class Main {
public static void main(String[] args) throws Exception {
byte[] header = {(byte) 0xFF, (byte) 0xFE};
var buffer = ByteBuffer.wrap(header).order(ByteOrder.BIG_ENDIAN);
System.out.println(Short.toUnsignedInt(buffer.getShort()));
System.out.println(buffer.remaining() + " bytes left");
}
}
65534 0 bytes left