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

  1. Start with Bytes 00 and 02 in hexadecimal
  2. Do this Read most significant byte first
  3. Result 2
The first byte contributes zero groups of 256. The second contributes two.

Apply it to a real problem

  1. Start with Packet header FF FE
  2. Do this Read its unsigned count
  3. Result 65,534
The two bytes encode 255 groups of 256 plus 254.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
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");
    }
}
Output
65534
0 bytes left

Official Java documentation