AlgoTales · Roadmap

Set/unset/toggle bits

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Setting, unsetting and toggling a bit means turning one chosen switch on, off, or flipping it, without disturbing the others. A small mask with just that bit lit does the job in a single step, so one number can safely hold many settings.

Practical use cases

  • Web app: Notification settings page. A user opens settings and ticks Email, SMS and Push. Each choice is one bit in a single number saved on their profile. Ticking sets the bit, unticking clears it, and a toggle switch flips it, all without touching the other choices or running extra queries.
  • Web app: Admin grants and revokes access. An admin gives a teammate delete permission and later removes it. The code turns on the delete bit with OR and turns it off with AND NOT, leaving read and write untouched. One column update changes exactly one permission, so no one loses rights by accident.
  • System: File permissions and hardware. Unix file modes, game state flags and hardware control registers are all numbers where each bit is a separate setting. Programs switch individual bits using these three moves, so a single byte can describe read, write and run rights for an owner, a group and everyone else, all at once.

The story: The Hostel Light Switches

Zoya's hostel had a panel of eight switches, one for each room on the corridor. A single number in the warden's notebook recorded which room lights were on: bit 0 for room 0, bit 1 for room 1, and so on. "If the notebook says 44, then rooms 2, 3 and 5 are lit," the warden explained.

The warden had four jobs. Turn on room 0 without touching the others. Turn off room 2 without touching the others. Flip room 5, whichever way it was. And peek: is room 3 lit?

Zoya built one tool for each: a mask, a number with a single 1 at the room's position (1 << room). To turn on: OR the mask in. To turn off: AND with the flipped mask. To flip: XOR the mask in. To peek: AND with the mask and see if anything is left.

These four tricks (set, clear, toggle, test) are the entire toolkit of bit manipulation. Once you own them, one integer can quietly hold 32 or 64 yes/no flags, and changing one never disturbs the others.

How to spot this problem, and where you need it

You keep one number holding many on or off settings and need to change just one without accidentally overwriting the others, or you are writing awkward code to rebuild the whole value every time.

Signs you need it

  • A single integer or string stores several flags, and updating one flag has previously reset the others.
  • You are reading or writing chmod-style numbers, status bytes or settings bitfields.
  • The task says turn on the k-th bit, clear it, flip it, or check whether it is set.

Where to use it in a project

  • Settings, preferences and permission screens that save many checkboxes in one column.
  • Game or workflow state, such as which levels are unlocked or which steps of a form are completed.

The solution

Build a mask by shifting 1 left by the bit position. To set, join the number and mask with OR. To unset, AND the number with the flipped mask. To toggle, XOR the number and mask. To test, AND them and see whether the result is non-zero. Only the chosen bit is affected, because the mask is zero everywhere else.

Payoff: Before: a rewrite of the whole settings value each time, with occasional lost options. After: one safe line per change, and other settings never move.

Explain it like I am 8

Imagine a row of light switches and a mask like a stencil with one hole. Looking through the hole you can turn that one light on, off or flip it, and every other light stays exactly as it was.

How it works, step by step

  1. Build the mask: mask = 1 << i is a number with only bit i switched on.
  2. Set bit i: n = n | mask. OR keeps ones and adds this one.
  3. Unset bit i: n = n & ~mask. The flipped mask protects all other bits and zeroes this one.
  4. Toggle bit i: n = n ^ mask. XOR flips just that bit.
  5. Test bit i: (n >> i) & 1 gives 1 if it is on and 0 otherwise.

The code in four languages

PHP

<?php
function setBit(int $n, int $i): int    { return $n | (1 << $i); }
function clearBit(int $n, int $i): int  { return $n & ~(1 << $i); }
function toggleBit(int $n, int $i): int { return $n ^ (1 << $i); }
function testBit(int $n, int $i): bool    { return (($n >> $i) & 1) === 1; }

function show(int $n): string { return str_pad(decbin($n), 8, '0', STR_PAD_LEFT); }

$n = 44;                                   // 00101100
echo "start   : " . show($n) . " ($n)
";
$n = setBit($n, 0);
echo "set 0   : " . show($n) . " ($n)
";   // 45
$n = clearBit($n, 2);
echo "clear 2 : " . show($n) . " ($n)
";   // 41
$n = toggleBit($n, 5);
echo "toggle 5: " . show($n) . " ($n)
";   // 9
$n = toggleBit($n, 5);
echo "toggle 5: " . show($n) . " ($n)
";   // 41 again
echo "bit 3 on? " . (testBit($n, 3) ? 'yes' : 'no') . "
";
echo "bit 2 on? " . (testBit($n, 2) ? 'yes' : 'no') . "
";

JavaScript

const setBit    = (n, i) => n | (1 << i);
const clearBit  = (n, i) => n & ~(1 << i);
const toggleBit = (n, i) => n ^ (1 << i);
const testBit     = (n, i) => ((n >> i) & 1) === 1;

const show = n => n.toString(2).padStart(8, '0');

let n = 44;                                // 00101100
console.log("start   : " + show(n) + " (" + n + ")");
n = setBit(n, 0);
console.log("set 0   : " + show(n) + " (" + n + ")");   // 45
n = clearBit(n, 2);
console.log("clear 2 : " + show(n) + " (" + n + ")");   // 41
n = toggleBit(n, 5);
console.log("toggle 5: " + show(n) + " (" + n + ")");   // 9
n = toggleBit(n, 5);
console.log("toggle 5: " + show(n) + " (" + n + ")");   // 41 again
console.log("bit 3 on? " + (testBit(n, 3) ? 'yes' : 'no'));
console.log("bit 2 on? " + (testBit(n, 2) ? 'yes' : 'no'));

Java

public class Main {
    static int setBit(int n, int i)    { return n | (1 << i); }
    static int clearBit(int n, int i)  { return n & ~(1 << i); }
    static int toggleBit(int n, int i) { return n ^ (1 << i); }
    static boolean testBit(int n, int i) { return ((n >> i) & 1) == 1; }

    // Show n as 8 binary digits.
    static String show(int n) {
        return String.format("%8s", Integer.toBinaryString(n)).replace(' ', '0');
    }

    public static void main(String[] args) {
        int n = 44;                                   // 00101100
        System.out.println("start   : " + show(n) + " (" + n + ")");
        n = setBit(n, 0);
        System.out.println("set 0   : " + show(n) + " (" + n + ")");   // 45
        n = clearBit(n, 2);
        System.out.println("clear 2 : " + show(n) + " (" + n + ")");   // 41
        n = toggleBit(n, 5);
        System.out.println("toggle 5: " + show(n) + " (" + n + ")");   // 9
        n = toggleBit(n, 5);
        System.out.println("toggle 5: " + show(n) + " (" + n + ")");   // 41 again
        System.out.println("bit 3 on? " + (testBit(n, 3) ? "yes" : "no"));
        System.out.println("bit 2 on? " + (testBit(n, 2) ? "yes" : "no"));
    }
}

Go

package main

import "fmt"

func setBit(n, i int) int    { return n | (1 << i) }
func clearBit(n, i int) int  { return n &^ (1 << i) }
func toggleBit(n, i int) int { return n ^ (1 << i) }
func testBit(n, i int) bool  { return (n>>i)&1 == 1 }

// show formats n as 8 binary digits.
func show(n int) string { return fmt.Sprintf("%08b", n) }

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	n := 44 // 00101100
	fmt.Printf("start   : %s (%d)\n", show(n), n)
	n = setBit(n, 0)
	fmt.Printf("set 0   : %s (%d)\n", show(n), n) // 45
	n = clearBit(n, 2)
	fmt.Printf("clear 2 : %s (%d)\n", show(n), n) // 41
	n = toggleBit(n, 5)
	fmt.Printf("toggle 5: %s (%d)\n", show(n), n) // 9
	n = toggleBit(n, 5)
	fmt.Printf("toggle 5: %s (%d)\n", show(n), n) // 41 again
	fmt.Println("bit 3 on?", yesNo(testBit(n, 3)))
	fmt.Println("bit 2 on?", yesNo(testBit(n, 2)))
}

Time: O(1) · Extra space: O(1). Each operation is a couple of CPU instructions, no matter how many bits the number holds.

Watch out for

  • Using n & mask to clear a bit. That keeps only that bit. You need n & ~mask.
  • Mixing up the position: bit 0 is the right-most bit, and counting starts at 0.
  • Comparing n & mask to 1 when testing a high bit. It returns the mask value (such as 8), so compare with !== 0 instead.

Quick check

  1. Which expression turns bit i ON without touching other bits?
    • n & (1 << i)
    • n | (1 << i)
    • n ^ (1 << i)
  2. Toggling the same bit twice leaves the number...
    • Doubled
    • Zero
    • Unchanged
  3. Which expression clears bit i?
    • n & ~(1 << i)
    • n | ~(1 << i)
    • n ^ (1 << i)