Bit Manipulation · Pattern 1 of 6

Bit basics: read, test and build numbers bit by bit

n & 1 reads the lowest bit and n >> 1 drops it, so a loop can walk through every bit. (n >> k) & 1 tests one bit, and res = (res << 1) | bit builds a number one bit at a time.

3 variations · 8 problems · 4 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Convert between decimal and binary (or another base)
  • Is bit k set? Is the number odd?
  • Reverse, add or validate numbers without the usual operators
  • Read a number given as a list of bits

The template

Basics
String toBinary(int n) {                   // n >= 0
    if (n == 0) return "0";
    StringBuilder sb = new StringBuilder();
    for (; n > 0; n >>= 1) sb.append(n & 1);   // lowest bit first
    return sb.reverse().toString();
}

boolean isKthBitSet(int n, int k) {
    return ((n >> k) & 1) == 1;                // bring bit k to the bottom
}

int reverseBits(int n) {                       // the 32 bits, treated as unsigned
    int res = 0;
    for (int i = 0; i < 32; i++) {
        res = (res << 1) | (n & 1);            // shift the next bit in
        n >>>= 1;                              // >>> so no sign bits come in
    }
    return res;
}

int getSum(int a, int b) {                     // a + b without + or -
    while (b != 0) {
        int carry = (a & b) << 1;              // where both bits are 1
        a ^= b;                                // sum without the carry
        b = carry;
    }
    return a;
}

The variations

  1. 1Convert between bases

    n & 1 (or n % 2) is the next digit and n >> 1 moves on; reverse at the end. Going the other way, res = res * 2 + bit (or (res << 1) | bit) reads bits from the most significant end. Base −2 is the same loop with remainders fixed to 0 or 1.

  2. 2Test one bit

    Shift the bit you want to the bottom and AND with 1, or AND with the mask 1 << k. Odd or even is just bit 0. UTF-8 bytes are told apart by their top bits, so the same test reads each byte's header.

  3. 3Shift bits in and out

    Take bits off one number with n & 1 and n >>> 1, and push them onto another with (res << 1) | bit. Adding without + is the same kind of loop: XOR adds without carrying, and (a & b) << 1 is the carry, until no carry is left.

    Worked example Reverse Bits Easy Read the solution
    Now you solve

Mistakes to avoid

  • Writing n & 1 << k and getting the precedence wrong: put brackets around every bit expression.
  • Reversing bits with >> in Java or JavaScript: a set top bit drags ones in from the left. Use >>>.
  • In JavaScript, returning a reversed 32-bit value without >>> 0 gives a negative number when the top bit is 1.

Mark it done once you can write the template from memory and you have solved the worked examples yourself.