Counting Trailing Zero Bits

Trailing zero count gives the number of consecutive zero bits starting at the least significant end of a nonzero word.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Read a value
  2. Specify what zero means
  3. Locate the lowest one by counting from the right
  4. Distinguish display width from the zero convention

Read a value

The pattern 101000 ends in three zeros. Its integer value is divisible by eight but not by sixteen. Binary position values show why every contributing term contains at least a factor of eight.

Specify what zero means

A machine instruction or library may define a special result for the all-zero value. An algorithm using the count to find the lowest set bit needs to handle that missing position. Sentinel values can express it.[1]

Locate the lowest one by counting from the right

In 10110000 the lowest set position is four. The unsigned value 176 is divisible by sixteen but not by thirty-two. Trailing zero count thus matches the largest exponent of a power of two dividing a positive integer. See binary positional weights.

Word       trailing zeros
10110000   4
00000001   0
10000000   7
00000000   needs a documented convention

Distinguish display width from the zero convention

Adding leading zero positions changes neither the lowest set position nor the count for a nonzero input. For zero, some operations return the fixed width and others require a nonzero input. Test zero directly before using the count as an index.

References

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