Set Bits Counter
Problem
Three small functions on an unsigned 32-bit value, no library calls, no lookup tables unless you build them yourself:
popcount(x)— number of bits set to 1.swapNibbles(b)— for a byte, exchange the high and low 4 bits.isPowerOfTwo(x)— true if exactly one bit is set (0is not a power of two).
This is the first screen for embedded roles. I care less about the answer than about whether you reach for the bit tricks naturally.
Examples
Example 1 — popcount(0b1011_0001) = 4, popcount(0) = 0, popcount(0xFFFFFFFF) = 32.
Example 2 — swapNibbles(0xAB) = 0xBA, swapNibbles(0x0F) = 0xF0. isPowerOfTwo(64) = true, isPowerOfTwo(96) = false, isPowerOfTwo(0) = false.
Constraints
- Inputs are unsigned 32-bit (or 8-bit for the nibble swap). In C, use
uint32_t/uint8_tand mask results. popcountshould beO(number of set bits)per the classicx &= x - 1trick; the naive 32-iteration loop is accepted as a warm-up.- No
__builtin_popcount; but tell me it exists and when you would use it.
What they look for
x & (x - 1) clears the lowest set bit, which gives both popcount and isPowerOfTwo (x && !(x & (x - 1))). Shifts and masks for the nibble swap, with awareness of integer promotion in C ((b << 4) becomes an int, so mask with 0xFF). Follow-ups go to reversing bits, counting trailing zeros, and the parallel-prefix popcount used by compilers.