Bitwise Operations

Working directly with the individual bits of an integer: masks, flags, shifts and classic tricks.

What is it?

Integers are stored as binary: a row of bits, each 0 or 1. Bitwise operators work on those bits one position at a time:

- AND (&): 1 only if both bits are 1. Used to test or clear bits. - OR (|): 1 if either bit is 1. Used to set bits. - XOR (^): 1 if the bits differ. Used to toggle bits. - NOT (~): flips every bit. - Left shift (<<): moves bits left, filling with 0. x << n is x * 2^n while it doesn't overflow. - Right shift (>>): moves bits right. x >> n is x / 2^n rounded toward negative infinity for signed values on most platforms.

A mask is a number with 1s in the positions you care about. Combined with AND, OR and XOR it lets you read or change specific bits. This is how flags work: many on/off settings packed into one integer, like Unix file permissions.

Negative integers are stored using two's complement: to negate a number, flip all its bits and add 1. This makes addition work the same way for positive and negative numbers.

Explain like I'm 10

Think of a row of light switches. A mask is a stencil laid over the switches. OR with the stencil turns on the switches it exposes, AND turns off everything it doesn't expose, and XOR flips the exposed ones. Shifting slides the whole row of switch positions left or right.

Examples

Flags with masks (C)

#define FLAG_READ    (1u << 0)   /* 0b001 */
#define FLAG_WRITE   (1u << 1)   /* 0b010 */
#define FLAG_EXECUTE (1u << 2)   /* 0b100 */

unsigned int permissions = 0;
permissions |= FLAG_READ | FLAG_WRITE;     /* set:    0b011 */
permissions &= ~FLAG_WRITE;                /* clear:  0b001 */
permissions ^= FLAG_EXECUTE;               /* toggle: 0b101 */

if (permissions & FLAG_EXECUTE) {          /* test: non-zero means set */
    puts("can execute");
}

Classic tricks (Python)

def is_power_of_two(n):
    return n > 0 and (n & (n - 1)) == 0     # a power of two has exactly one 1 bit

def count_set_bits(n):                      # Kernighan's method, for n >= 0
    count = 0
    while n:
        n &= n - 1                          # clears the lowest set bit
        count += 1
    return count

def lowest_set_bit(n):
    return n & -n                           # two's complement isolates it

a, b = 6, 9
a ^= b; b ^= a; a ^= b                      # XOR swap: a=9, b=6 (curiosity, not practice)

print(is_power_of_two(64), count_set_bits(0b1011), lowest_set_bit(12))  # True 3 4

n - 1 flips the lowest 1 bit to 0 and every 0 below it to 1, so n & (n - 1) removes the lowest set bit. Modern languages also have built-ins: int.bit_count() in Python 3.10+, Integer.bitCount in Java, __builtin_popcount in GCC/Clang.

How it works

Bit positions. In an 8-bit value, bit 0 is the least significant (worth 1) and bit 7 the most significant (worth 128). 1 << k builds a mask with only bit k set.

Two's complement. For an n-bit signed integer, the top bit has weight -2^(n-1) instead of +2^(n-1). So in 8 bits, 11111111 is -1 and 10000000 is -128. Negation is ~x + 1. This gives one zero, an asymmetric range (-128 to 127), and lets the CPU use the same adder circuit for signed and unsigned values.

Shifts. - Left shift multiplies by powers of two but discards bits shifted off the top. In C, shifting a signed value into or past the sign bit, or shifting by a count greater than or equal to the bit width, is undefined behaviour. - Right shift on unsigned values fills with 0 (logical shift). On signed values most platforms copy the sign bit (arithmetic shift), so -8 >> 1 is -4. Java and JavaScript have >>> for an explicit logical right shift.

Language quirks. JavaScript converts operands of bitwise operators to 32-bit signed integers, so 2 ** 32 | 0 is 0. Python integers have unlimited size, so ~5 is -6 and there's no overflow; mask with & 0xFFFFFFFF to emulate a fixed width.

Precedence. In C-family languages &, ^ and | bind more loosely than ==, so x & 1 == 0 means x & (1 == 0). Use parentheses.

bit:  7 6 5 4 3 2 1 0
 x      =     0 0 1 0 1 1 0 0   (44)
 mask   =     0 0 0 0 1 0 0 0   (1 << 3)

 x & mask  =  0 0 0 0 1 0 0 0   test bit 3  -> non-zero, so it's set
 x | 0x01  =  0 0 1 0 1 1 0 1   set bit 0
 x & ~mask =  0 0 1 0 0 1 0 0   clear bit 3
 x ^ mask  =  0 0 1 0 0 1 0 0   toggle bit 3
 x << 1    =  0 1 0 1 1 0 0 0   (88)
 x >> 2    =  0 0 0 0 1 0 1 1   (11)

 Two's complement, 8-bit:  5 = 00000101
                          ~5 = 11111010
                       ~5 + 1 = 11111011 = -5

Why does it exist?

Hardware works in bits, and bitwise instructions are among the cheapest a CPU has. They let you pack many booleans into one word, read and write hardware registers and binary file formats, and implement hashing, compression, cryptography and graphics efficiently. Two's complement exists because it makes signed arithmetic use the same circuits as unsigned arithmetic.

When to use it

- Flags and permission sets (file modes, feature toggles, options passed to system calls). - Parsing and writing binary formats and network protocols (headers, checksums, packed fields). - Embedded and driver code that reads or writes hardware registers. - Compact data structures: bitsets, Bloom filters, chess bitboards. - Hashing, random number generators, and algorithm problems over subsets (iterating all subsets of n items as the numbers 0 to 2^n - 1).

When not to use it

- Don't replace * 2 or / 4 with shifts for speed; compilers already do this, and the shift version is less clear (and wrong for negative division in many languages). - Don't use the XOR swap in real code; a temporary variable is clearer and as fast, and XOR swap zeroes the value if both names refer to the same location. - Don't pack flags into an int in high-level code when an enum set, a list of booleans or a small object would be more readable and the space doesn't matter.

Common mistakes

  • Forgetting precedence: if (flags & MASK == MASK) parses as flags & (MASK == MASK). Write (flags & MASK) == MASK.

  • Confusing logical and bitwise operators: && vs &, || vs |, and ! vs ~.

  • Shifting a 32-bit value by 32 or more bits, or shifting 1 (a signed int) into the sign bit in C; both are undefined. Use 1u or 1ull for high bits.

  • Forgetting that JavaScript bitwise operators truncate numbers to 32-bit signed integers.

  • Assuming right shift of a negative number is the same as division: -7 >> 1 is -4 (rounds toward negative infinity), while -7 / 2 in C or Java is -3.

Practice exercises

  1. Easy:

    Write functions set_bit(n, k), clear_bit(n, k), toggle_bit(n, k) and is_bit_set(n, k), and test them on several values.

  2. Medium:

    Given an array where every number appears twice except one, find the single number in O(n) time and O(1) space using XOR. Then explain why it works.

  3. Hard:

    Print every subset of a list of n items by iterating the integers 0 to 2^n - 1 and using bit k to decide whether item k is included. Then write a function that returns the next larger integer with the same number of set bits (Gosper's hack).

Interview questions

How do you check if a number is a power of two?

n > 0 && (n & (n - 1)) == 0. A power of two has exactly one set bit; subtracting 1 clears it and sets all lower bits, so the AND is zero only for powers of two.

How do you set, clear, toggle and test bit k?

Set: n | (1 << k). Clear: n & ~(1 << k). Toggle: n ^ (1 << k). Test: (n >> k) & 1 or (n & (1 << k)) != 0.

What is two's complement and why is it used?

A signed integer encoding where the top bit has negative weight; -x is ~x + 1. It has a single zero, makes addition and subtraction identical to unsigned arithmetic at the bit level, and so needs no special hardware for signed numbers.

What is the difference between logical and arithmetic right shift?

Logical shift fills vacated high bits with 0 and is used for unsigned values. Arithmetic shift copies the sign bit, preserving the sign of negative numbers. Java and JavaScript use >> for arithmetic and >>> for logical.

How do you count the set bits in an integer?

Kernighan's loop: repeat n &= n - 1 and count iterations, which runs once per set bit. In practice use the CPU's popcount via built-ins such as __builtin_popcount, Integer.bitCount, or Python's int.bit_count().

How does XOR help find the one non-duplicated number in an array?

XOR is associative and commutative, x ^ x = 0 and x ^ 0 = x. XORing all elements cancels every pair and leaves the single unpaired value, in O(n) time and O(1) space.

What does `n & -n` compute?

The lowest set bit of n as a value. In two's complement, -n is ~n + 1, which flips all bits above the lowest set bit and keeps that bit, so AND leaves only it. Fenwick trees use this.

Why should you avoid the XOR swap trick?

It's less readable, usually no faster than using a temporary (compilers optimize swaps well, and the XORs create a dependency chain), and if both operands are the same memory location it zeroes the value instead of swapping.

Why might `x & 1 == 0` give the wrong result in C or JavaScript?

Equality binds tighter than bitwise AND, so it parses as x & (1 == 0), which is x & 0 (or x & false), always 0. Write (x & 1) == 0.

How would you store a set of 1 million booleans compactly, and what are the trade-offs?

A bitset: an array of 64-bit words, bit i in word i/64 at position i%64, using about 125 KB instead of roughly 1 MB of bytes. Operations are fast word-wide ANDs and ORs. The trade-off is slightly more complex indexing, and concurrent updates to bits in the same word need atomic operations.