Unsigned Integers
An unsigned integer uses all its bits for magnitude, representing whole numbers from zero upward.
Definition
An unsigned integer interprets its bit pattern as a plain binary number with no sign. With n bits the representable range is 0 to 2ⁿ−1. An 8-bit unsigned byte spans 0 to 255.
Range and width
Each added bit doubles the count of values. Common widths are 8, 16, 32, and 64 bits, giving maxima of 255, 65535, about 4.29 billion, and about 1.8×10¹⁹ respectively.
Arithmetic and wraparound
Unsigned arithmetic is modular: results are taken modulo 2ⁿ. Adding 1 to the maximum value wraps around to 0. This is defined, predictable behavior, unlike signed overflow in some languages.
When to use it
- Sizes, counts, and array indices that cannot be negative
- Bit fields and flags where each bit is meaningful
- Memory addresses and hardware registers
- Hash values and checksums
Pitfalls
Mixing signed and unsigned values in comparisons can produce surprises: a negative signed value converted to unsigned becomes a large positive number. Subtracting a larger unsigned value from a smaller one wraps rather than going negative.
# Emulate 8-bit unsigned wraparound
MASK = 0xFF
x = (255 + 1) & MASK
print(x) # 0