Bit Manipulation
Bit manipulation uses C's bitwise operators to pack flags, test powers of two, and compute on integers as arrays of bits. The machine already works this way. The operators let you say so.
Detailed Explanation
& | ^ ~ << >> act on the binary representation. & is useful as a mask: x & 1 is the low bit, x & (x - 1) clears the lowest set bit, x & -x isolates it (two's complement). | sets bits. ^ toggles and is also xor, the basis of "swap without a temp" and of parity. ~ flips every bit of the promoted operand. Shifts move the pattern; on unsigned types, >> is a logical shift. On signed types, a right shift of a negative value is implementation-defined (usually arithmetic) and a left shift of a negative value or out of range is undefined.
Flags live in an unsigned integer. #define READ (1u << 0) and friends, then flags |= READ, flags &= ~READ, if (flags & READ). Use unsigned so shifts are defined and so ~ does not produce a negative signed value you then shift.
Bitsets larger than a word are arrays of unsigned long. Index bit i as words[i / WIDTH] & (1ul << (i % WIDTH)). This is how you store visited for dense vertex ids when a char[] is too fat.
Interview tricks cluster here. Count set bits with Kernighan's loop (n &= n - 1). Test a power of two with n && !(n & (n - 1)). Swap two integers with xor only if they are not the same location. Reverse bits, find the single number that appears once, subset enumeration with mask from 0 to (1u << n) - 1.
Readability is the cost. A line of masks without names is a defect. Name the mask. Comment the invariant ("low 5 bits are the length"). Prefer bool fields in a struct until you have measured the packing win or you are talking to hardware.
Code Examples
#include <stdio.h>
#include <stdint.h>
static int popcount(uint32_t n)
{
int c = 0;
while (n) {
n &= n - 1; /* clear lowest set bit */
c++;
}
return c;
}
static int is_pow2(uint32_t n)
{
return n != 0 && (n & (n - 1)) == 0;
}
int main(void)
{
printf("%d %d\n", popcount(13u), is_pow2(8u)); /* prints: 3 1 */
return 0;
}#include <stdio.h>
#include <stdint.h>
enum { READ = 1u << 0, WRITE = 1u << 1, EXEC = 1u << 2 };
int main(void)
{
uint32_t flags = 0;
flags |= READ | WRITE;
flags &= ~WRITE;
printf("%u\n", (unsigned)(flags & READ)); /* prints: 1 */
return 0;
}Common Gotchas
Shifting by the width of the type or more is undefined behavior
`1u << 32` on a 32-bit `unsigned` is UB, even if you "know" it should be zero.
Left-shifting a negative `int` is undefined behavior
do bit work on unsigned types.
`~` on a signed `int` promotes and then produces a negative
write `~0u` or `~(uint32_t)0`.
`x ^ x` is zero, and `x ^= y; y ^= x; x ^= y` corrupts if `x` and `y` alias
use a temporary.