Bit Manipulation

Bitwise AND, OR, XOR, NOT and shifts, testing, setting, clearing and toggling bits, x & (x - 1) tricks, counting set bits, the XOR single-number trick and generating subsets with bitmasks.

Computers store integers in binary, and bitwise operators work on all the bits at once in a single instruction. Bit tricks give compact, very fast solutions to many problems, and GATE often asks what a short bitwise expression computes.

The operators

OperatorJava / C / PythonRule per bit
ANDa & b1 only if both are 1
ORa | b1 if either is 1
XORa ^ b1 if they differ
NOT~aFlips every bit (~a = −a − 1 in two's complement)
Left shifta << kMultiply by 2ᵏ
Right shifta >> kDivide by 2ᵏ (rounding down for non-negative a)

XOR facts: a ^ a = 0, a ^ 0 = a, and XOR is commutative and associative, so pairs cancel in any order.

Working with bit i

1bit 50bit 41bit 31bit 20bit 10bit 0gateshala.com
x = 44 in binary (bit 5 on the left, bit 0 on the right)
TaskExpression
Test bit i(x >> i) & 1
Set bit ix | (1 << i)
Clear bit ix & ~(1 << i)
Toggle bit ix ^ (1 << i)
Lowest set bitx & -x
Clear lowest set bitx & (x - 1)
Is x a power of 2?x > 0 && (x & (x - 1)) == 0

Counting set bits (Kernighan): repeat x &= x − 1 until x = 0; the number of steps is the number of 1s. It runs in O(number of set bits).

Bitmasks as sets

An n-bit integer can stand for a subset of n items: bit i is 1 when item i is in the set. All 2ⁿ masks from 0 to 2ⁿ − 1 list every subset, which is the basis of bitmask DP (for example the travelling salesman problem in O(2ⁿ n²)). Union is |, intersection &, and difference a & ~b.

The code

public class Main {
    static int popcount(int x) {          // Kernighan: each step clears the lowest set bit
        int c = 0;
        while (x != 0) { x &= x - 1; c++; }
        return c;
    }

    public static void main(String[] args) {
        int x = 44;                       // 101100 in binary
        System.out.println("x = " + x + " = " + Integer.toBinaryString(x));
        System.out.println("bit 2 set? " + ((x >> 2 & 1) == 1));
        System.out.println("set bit 0:   " + (x | 1));
        System.out.println("clear bit 3: " + (x & ~(1 << 3)));
        System.out.println("toggle bit 5: " + (x ^ (1 << 5)));
        System.out.println("lowest set bit: " + (x & -x));
        System.out.println("set bits: " + popcount(x));
        System.out.println("64 is a power of 2? " + ((64 & 63) == 0));

        int[] a = {7, 3, 5, 3, 7};        // every value twice except one
        int single = 0;
        for (int v : a) single ^= v;      // pairs cancel: v ^ v = 0
        System.out.println("appears once: " + single);

        int[] items = {1, 2, 3};
        StringBuilder all = new StringBuilder();
        for (int mask = 0; mask < (1 << items.length); mask++) {   // each mask is one subset
            StringBuilder s = new StringBuilder("{");
            for (int i = 0; i < items.length; i++)
                if ((mask >> i & 1) == 1) s.append(s.length() > 1 ? "," : "").append(items[i]);
            all.append(mask > 0 ? " " : "").append(s).append("}");
        }
        System.out.println("subsets: " + all);
    }
}
Output
x = 44 = 101100
bit 2 set? true
set bit 0:   45
clear bit 3: 36
toggle bit 5: 12
lowest set bit: 4
set bits: 3
64 is a power of 2? true
appears once: 5
subsets: {} {1} {2} {1,2} {3} {1,3} {2,3} {1,2,3}

GATE-style practice questions

GATE-styleNAT · numerical answer

What is the value of 29 & (29 − 1)?

Show answer and explanationAnswer: 28

29 = 11101 and 28 = 11100; x & (x − 1) clears the lowest set bit, giving 11100 = 28.

GATE-styleNAT · numerical answer

How many set bits does 255 ^ 170 have?

Show answer and explanationAnswer: 4

11111111 ^ 10101010 = 01010101, which has 4 ones.

GATE-styleNAT · numerical answer

What does this program print?

#include <stdio.h>
int main(void) {
    int x = 12, c = 0;
    while (x) { c += x & 1; x >>= 1; }
    printf("%d\n", c);
    return 0;
}
Show answer and explanationAnswer: 2

The loop counts the 1 bits of 12 = 1100: two of them.

GATE-styleMCQ · one correct answer

For a positive integer x, the expression x & (x − 1) equals 0 exactly when:

Show answer and explanationAnswer: A

A power of 2 has a single 1 bit; clearing it leaves 0.

GATE-styleMCQ · one correct answer

Which expression gives the value of the lowest set bit of x (for x > 0)?

Show answer and explanationAnswer: B

In two's complement, −x = ~x + 1, which keeps only the lowest 1 bit in common with x.