Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java unsigned int parsing: preserve 32-bit protocol values

Last updated: 5 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

Integer.parseUnsignedInt accepts decimal values through 2^32-1 but stores the bits in a signed int, so ordinary printing can appear negative.

Keep the protocol interpretation

A device counter may use every bit of a 32-bit unsigned field. The maximum value parses into an int with all bits set, which prints as -1 under signed formatting. Convert with Integer.toUnsignedLong or toUnsignedString before display or arithmetic that expects the unsigned value.

The fixture prints all three views of one field. Exact narrowing applies when an external number must actually fit a signed int; it is not the same as retaining an unsigned bit pattern.

Reject values outside the field width

An input larger than 2^32-1 fails parsing. Do not strip the sign or cast from long without checking the protocol width; that would silently wrap a different value into the field.

Working program

Java
public class DeviceSequenceBits {
    public static void main(String[] args) {
        int encoded = Integer.parseUnsignedInt("4294967295");
        System.out.println("signed=" + encoded);
        System.out.println("unsigned=" + Integer.toUnsignedLong(encoded));
        System.out.println("text=" + Integer.toUnsignedString(encoded));
    }
}

Output

Output
signed=-1
unsigned=4294967295
text=4294967295

Cost and ownership

The conversions use fixed-width primitive storage. Parsing cost grows with input length, so bound the field before conversion. A signed int can store the bits, but its ordinary operators and formatting need deliberate unsigned handling.

Common Mistakes

  • Do not interpret the signed printout as the unsigned protocol value.
  • Do not cast an unchecked long into an unsigned 32-bit field.
  • Do not confuse bit preservation with signed numeric range validation.

Read next

Java BigInteger.intValueExact: reject a narrowing conversion, Java operators and numeric promotion, Java checked integer arithmetic: reject overflow before updating state, Java ByteBuffer byte order: decode the protocol before reading integers.

java
numeric
unsigned-integer-parsing
Storage details