Reading history

Bit Manipulation in C: Operators, Masks and Tricks

7 min read 0 views

Learn bit manipulation in C: AND, OR, XOR, NOT and shifts, setting and testing bits, counting 1 bits, powers of two, the XOR trick and bitmask subsets.

Every integer is stored as a row of bits, and C lets you work on those bits directly. Bit manipulation uses the operators &, |, ^, ~, << and >> to test, set and combine individual bits. It packs many true/false flags into one number, speeds up some calculations, and powers well-known tricks such as finding the one unpaired number in an array or listing all subsets of a set. It also explains how structures like the Fenwick tree work.

In this lesson you will learn

  • The six bitwise operators and what each one does
  • Setting, clearing, toggling and testing a single bit
  • Counting 1 bits and checking powers of two
  • The XOR trick for finding an unpaired number
  • Generating every subset with a bitmask

You should know operators in C and binary numbers.

Bitwise Operators

#include <stdio.h>

/* Print the lowest 8 bits of x */
static void bits8(unsigned x) {
    for (int i = 7; i >= 0; i--) putchar((x >> i) & 1u ? '1' : '0');
}

int main(void) {
    unsigned a = 12, b = 10;                 /* 00001100 and 00001010 */
    printf("a      = "); bits8(a); printf(" (%u)\n", a);
    printf("b      = "); bits8(b); printf(" (%u)\n", b);
    printf("a & b  = "); bits8(a & b); printf(" (%u)  AND: 1 where both are 1\n", a & b);
    printf("a | b  = "); bits8(a | b); printf(" (%u)  OR: 1 where either is 1\n", a | b);
    printf("a ^ b  = "); bits8(a ^ b); printf(" (%u)   XOR: 1 where they differ\n", a ^ b);
    printf("a << 2 = "); bits8(a << 2); printf(" (%u)  multiply by 4\n", a << 2);
    printf("a >> 2 = "); bits8(a >> 2); printf(" (%u)   divide by 4\n", a >> 2);
    printf("~a     = "); bits8(~a); printf("       NOT: every bit flipped (low 8 shown)\n");

    /* Working with single bits: set, clear, toggle, test */
    unsigned flags = 0;
    flags |= 1u << 3;                        /* set bit 3 */
    flags |= 1u << 0;                        /* set bit 0 */
    printf("\nflags after setting bits 0 and 3: "); bits8(flags); printf("\n");
    flags &= ~(1u << 0);                     /* clear bit 0 */
    flags ^= 1u << 5;                        /* toggle bit 5 */
    printf("after clearing 0 and toggling 5:  "); bits8(flags); printf("\n");
    printf("is bit 3 set? %s, is bit 4 set? %s\n", (flags >> 3) & 1u ? "yes" : "no", (flags >> 4) & 1u ? "yes" : "no");
    return 0;
}

Output

a      = 00001100 (12)
b      = 00001010 (10)
a & b  = 00001000 (8)  AND: 1 where both are 1
a | b  = 00001110 (14)  OR: 1 where either is 1
a ^ b  = 00000110 (6)   XOR: 1 where they differ
a << 2 = 00110000 (48)  multiply by 4
a >> 2 = 00000011 (3)   divide by 4
~a     = 11110011       NOT: every bit flipped (low 8 shown)

flags after setting bits 0 and 3: 00001001
after clearing 0 and toggling 5:  00101000
is bit 3 set? yes, is bit 4 set? no
  • bits8 prints the lowest 8 bits by shifting each bit to position 0 and masking it with & 1.
  • & (AND) gives 1 only where both numbers have 1; | (OR) where either has 1; ^ (XOR) where they differ.
  • << k shifts left and multiplies by 2k; >> k shifts right and divides by 2k, dropping any remainder.
  • ~ flips every bit. Only the low 8 bits are shown; an unsigned has 32 bits on most systems.
  • The standard single-bit patterns use a mask 1u << k: set with x |= mask, clear with x &= ~mask, toggle with x ^= mask, and test with (x >> k) & 1.
  • Use unsigned types for bit work. Shifting a 1 into the sign bit of a signed int, or shifting a negative value left, is undefined behaviour in C.

Classic Bit Tricks

#include <stdio.h>

static int popcount(unsigned x) {          /* Brian Kernighan: remove the lowest 1 each time */
    int count = 0;
    while (x) { x &= x - 1; count++; }
    return count;
}

static int is_power_of_two(unsigned x) { return x != 0 && (x & (x - 1)) == 0; }

int main(void) {
    /* Counting 1 bits and testing powers of two */
    unsigned tests[] = {0, 1, 6, 16, 255, 1024};
    for (int i = 0; i < 6; i++)
        printf("%5u: %2d one bits, power of two: %s\n", tests[i], popcount(tests[i]),
               is_power_of_two(tests[i]) ? "yes" : "no");

    /* XOR trick: every number appears twice except one */
    int a[] = {4, 7, 2, 7, 4, 9, 2};
    int single = 0;
    for (int i = 0; i < 7; i++) single ^= a[i];          /* pairs cancel out: x ^ x = 0 */
    printf("\nthe number without a pair: %d\n", single);

    /* Even or odd, and the lowest set bit */
    printf("13 is %s, lowest set bit of 12 is %u\n", (13 & 1) ? "odd" : "even", 12u & -12u);

    /* Generate every subset of {A, B, C} with a bitmask */
    const char items[] = {'A', 'B', 'C'};
    printf("subsets:");
    for (unsigned mask = 0; mask < (1u << 3); mask++) {
        printf(" {");
        for (int i = 0; i < 3; i++)
            if (mask & (1u << i)) putchar(items[i]);
        printf("}");
    }
    printf("\n");
    return 0;
}

Output

    0:  0 one bits, power of two: no
    1:  1 one bits, power of two: yes
    6:  2 one bits, power of two: no
   16:  1 one bits, power of two: yes
  255:  8 one bits, power of two: no
 1024:  1 one bits, power of two: yes

the number without a pair: 9
13 is odd, lowest set bit of 12 is 4
subsets: {} {A} {B} {AB} {C} {AC} {BC} {ABC}
  • x & (x - 1) removes the lowest 1 bit, because subtracting 1 flips that bit and every 0 below it. Repeating it until x is 0 counts the 1 bits in as many steps as there are ones (Brian Kernighan’s method). GCC also offers __builtin_popcount.
  • A power of two has exactly one 1 bit, so removing it leaves 0: x && !(x & (x - 1)). The x != 0 test excludes zero.
  • XOR has two handy properties: x ^ x = 0 and x ^ 0 = x, and the order does not matter. XOR-ing all numbers cancels every pair and leaves the one without a partner, using O(1) memory. The unique number lesson explores this further.
  • n & 1 is 1 for odd numbers. x & -x keeps only the lowest set bit, the key step in a Fenwick tree.
  • For a set of n items, each number from 0 to 2n − 1 is a bitmask describing one subset: bit i says whether item i is included. Looping over all masks lists all 2n subsets.

Bit Manipulation Cheat Sheet

TaskExpression
Test bit k(x >> k) & 1
Set bit kx |= 1u << k
Clear bit kx &= ~(1u << k)
Toggle bit kx ^= 1u << k
Remove lowest 1 bitx & (x - 1)
Keep lowest 1 bitx & -x
Is power of two?x && !(x & (x - 1))
Is odd?x & 1
Multiply / divide by 2kx << k / x >> k (unsigned)

Common Mistakes

  1. Operator precedence: x & 1 == 0 means x & (1 == 0). Always write (x & 1) == 0.
  2. Shifting by the type’s width or more, such as 1u << 32 on a 32-bit unsigned, which is undefined.
  3. Mixing up & and &&: & works on bits, && on true/false values.
  4. Using signed integers for bit masks.

Practice Exercises

Exercise 1. Swap two unsigned integers without a temporary variable.

Show answer
a ^= b;
b ^= a;   /* b now holds the original a */
a ^= b;   /* a now holds the original b */

It works, but a temporary variable is clearer and just as fast; it also fails if a and b are the same variable.

Exercise 2. Store the days a shop is open (Sat to Fri, bits 0 to 6) in one byte, with Saturday and Monday open.

Show answer
unsigned char open = 0;
open |= 1u << 0;   /* Saturday */
open |= 1u << 2;   /* Monday   */
int monday_open = (open >> 2) & 1;   /* 1 */

Frequently Asked Questions

Is x << 1 faster than x * 2?

Modern compilers turn x * 2 into a shift automatically when it is faster. Write whichever makes the meaning clearer; use shifts when you are really working with bits.

Where is bit manipulation used in real programs?

In file permissions (read, write and execute flags), network masks in IP addresses, graphics and colour values, compression, cryptography, chess engines (bitboards) and compact sets of flags in operating systems.

Summary

  • &, |, ^, ~, << and >> work on individual bits.
  • Use a mask 1u << k to set, clear, toggle or test bit k.
  • x & (x - 1) and x & -x power many tricks.
  • Bitmasks represent subsets; XOR cancels pairs.

Next: Cycle Detection and Bipartite Graphs in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *