Sub topic 9
Power-of-two capacity and bit masks
This chapter assumes you can write a ring buffer with head and tail indices and modulo wraparound. It also assumes you know what bitwise AND does and that you can read short C and Python.
Why replace modulo
The basic buffer wraps an index with (index + 1) % capacity. That is correct for any capacity. The cost is a division, and on small microcontrollers without a hardware divider, division is slow. If the capacity is a power of two, you can replace the division with one bitwise AND.
How the mask works
A power of two has a single 1 bit in binary. Subtracting 1 turns that bit into 0 and sets every lower bit to 1. For a capacity of 8:
| Value | Binary |
|---|---|
| 8 (capacity) | `1000` |
| 7 (mask, `capacity - 1`) | `0111` |
| 13 | `1101` |
| 13 & 7 | `0101` = 5 |
| 13 % 8 | 5 |
The AND keeps only the low bits, and those low bits are the remainder after dividing by the capacity. For non-negative i and a power-of-two cap, i & (cap - 1) equals i % cap.
The check below shows the equivalence, and shows that it fails when the capacity is not a power of two:
for cap in (8, 6):
mask = cap - 1
print(cap, all((i & mask) == (i % cap) for i in range(100)))This prints 8 True and 6 False. With a capacity of 6 the mask is 101, which skips slot 1 and slot 3 or more. A buffer built this way silently overwrites and loses data.
Free-running indices
Masking also lets you stop wrapping the indices themselves. Let head and tail count upward forever, and apply the mask only when you index the array:
- The slot for an index is
index & (CAP - 1). - The number of stored items is
tail - head. - The buffer is empty when
tail == head. - The buffer is full when
tail - head == CAP.
This is the third way to tell full from empty. You need no count field and no spare slot, and all CAP slots are usable.
The indices eventually overflow. Unsigned arithmetic in C wraps modulo 2^32, so tail - head is still correct. The slot mapping stays continuous only if CAP divides 2^32, which every power of two up to 2^32 does.
#include <stdint.h>
#include <stdio.h>
int main(void) {
uint32_t head = 0xFFFFFFFEu;
uint32_t tail = head + 3u; /* wraps around to 1 */
printf("count=%u slot=%u\n",
(unsigned)(tail - head), (unsigned)(head & 7u));
return 0;
}The output is count=3 slot=6. The three items sit in slots 6, 7, and 0. The index passes through 0xFFFFFFFF to 0, and the mask maps those to slot 7 and slot 0.
Enforcing the constraint
Check the capacity once, in the constructor, rather than trusting callers. n & (n - 1) clears the lowest set bit, so the result is 0 only for powers of two:
def is_power_of_two(n):
return n > 0 and n & (n - 1) == 0
def round_up_pow2(n):
return 1 << (n - 1).bit_length() # n >= 1
print(is_power_of_two(8), is_power_of_two(6)) # True False
print(round_up_pow2(5), round_up_pow2(8)) # 8 8If a caller asks for 1000 slots, rounding up to 1024 wastes a little memory and keeps the mask valid.
Common mistakes
- Using a non-power-of-two capacity with a mask. The code runs and gives wrong slots. Validate in the constructor or use a fixed
#definewith a compile-time check. - Using signed indices. Signed overflow is undefined behavior in C. Use
uint32_torsize_t. - Choosing a capacity that does not divide the index range. With free-running indices, 8-bit indices need
CAPof 256 or less, and it must be a power of two. - Expecting free-running indices in Python. Python integers never overflow, so they grow without bound. This is correct but slower for huge values. Mask them if you want to emulate fixed-width behavior.
Exercise
A ring buffer has CAP = 16 and free-running uint32_t indices with head = 37 and tail = 50. How many items are stored, and which array slot will the next push write to?
Show answer
The count is tail - head = 13. The next push writes to slot tail & 15 = 50 & 15 = 2, because 50 is 110010 in binary and its low four bits are 0010. The buffer is not full, since 13 is less than 16.