The Range of an Unsigned Bit Field

Find the smallest and largest unsigned integers a field of a given bit width can hold.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Compute a small maximum
  2. Reuse the range at a boundary
  3. Derive the maximum from setting every bit
  4. Check a size limit before writing the field

A field of \(w\) bits has \(2^w\) possible patterns. Interpreted as unsigned integers, they represent zero through \(2^w-1\).

Compute a small maximum

Four bits yield values 0 through 15. The pattern 1111 gives \(8+4+2+1=15\). Adding one would require 10000 in ordinary binary notation.

Reuse the range at a boundary

For a four-bit protocol field, validate 0, 15, and the two outside values minus 1 and 16. An ordinary language integer may represent all four even when the field cannot. See fixed-width integers.[1]

Derive the maximum from setting every bit

In an unsigned field five bits wide, the weights are one, two, four, eight and sixteen. Setting them all gives thirty-one. There are thirty-two values because zero is included. See powers and binary digits.

Minimum 00000 = 0
Middle  10000 = 16
Maximum 11111 = 31
Value 32 requires 100000, six bits

Check a size limit before writing the field

A width of \(w\) has \(2^w\) patterns but the largest unsigned value is \(2^w-1\). A function should choose how to handle a larger value or a negative value. Check both the last valid and first invalid integer, including an exact power of two.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩