AlgoTales · Roadmap

Bit masks

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

Where you will meet this in real life

A bit mask is a number used as a stencil: it picks out, switches or tests chosen bits. Counting upward through all masks of n bits also lists every combination of n yes or no choices, which makes it a neat way to try all subsets.

Practical use cases

  • Web app: Role checks in an admin panel. Each menu item in a dashboard needs a certain set of rights. The page builds a mask for the item and ANDs it with the logged-in user's rights. If the result equals the mask, the menu item shows; otherwise it stays hidden. One line replaces a long chain of if-statements.
  • Web app: Trying every pizza topping combination. A food delivery app wants to show the best-value combo from 8 toppings. Counting from 0 to 255 gives every possible choice, with each bit meaning topping in or out. Each number is checked for price and rating, and the best wins, in under a millisecond.
  • System: Network masks. A subnet mask like 255.255.255.0 is a stencil that keeps the network part of an address and hides the machine part. Routers apply it with AND to decide where to send each packet, so one tiny number tells them which addresses are neighbours and which must be sent onward to the wider internet.

The story: Raju's Pizza Toppings

Raju had started making pizzas on weekends, with three toppings: paneer, onion and capsicum. Customers could order any combination, including a plain one. Raju kept forgetting how many combinations there were, and wrote every order on a long slip.

Mira had a simpler idea. "Give each topping a bit. Paneer is bit 0, onion bit 1, capsicum bit 2. A customer's order is one small number: 5 is 101, meaning paneer and capsicum." The same number could be stored on a tiny slip, compared quickly and passed around.

Then Kabir asked, "How many different pizzas are possible?" Mira counted on the board: 0, 1, 2, 3, 4, 5, 6, 7. "Every number from 0 to 7 is a different combination. Count up and you visit every possible pizza, once each, with no repeats." That is 8 pizzas, because each of the 3 toppings is either in or out (2 × 2 × 2).

A number used this way is a bit mask: it stands for a set of things. Operations on masks become set operations: OR joins two sets, AND finds what they share, and a loop from 0 to 2n - 1 enumerates every subset. This is a favourite weapon in programming contests.

How to spot this problem, and where you need it

You must test or change several options at once, or look at every possible combination of a small set of choices, and want a compact, quick way to represent each combination.

Signs you need it

  • You need to know whether a user has all of several rights at once, or any of them.
  • The problem has up to about 20 items and asks for the best subset or every subset.
  • A set of items is kept as an array of booleans and copying or comparing sets is slow.

Where to use it in a project

  • Authorisation code that checks combined rights for pages, buttons and API endpoints.
  • Small optimisation features, such as choosing the best combination of coupons, add-ons or delivery slots.

The solution

Give every item a bit. A mask is a number with a 1 for every chosen item. To test for all items, AND the value with the mask and compare with the mask. To test for any, check that the AND is not zero. To walk through every subset of n items, loop a counter from 0 to 2 to the power n minus 1 and read each counter as a mask.

Payoff: Before: nested if-statements per permission. After: one AND per check, and all 256 topping combinations tried in a blink.

Explain it like I am 8

Imagine a row of tiny switches, one per topping. A switch up means "yes, include it". The whole row of switches is one number. Counting up through all the numbers shows you every possible combination of switches.

How it works, step by step

  1. Give each item a bit position: item 0 is bit 0, item 1 is bit 1, and so on.
  2. A mask is a set: bit i on means item i is in the set.
  3. Combine sets: a | b is the union, a & b the overlap, a & ~b items in a but not b.
  4. Ask a question: mask & (1 << i) is non-zero when item i is in the set.
  5. List every subset of n items by looping the mask from 0 to (1 << n) - 1.

The code in four languages

PHP

<?php
// Permission flags: each is one bit.
const READ = 1;     // 001
const WRITE = 2;    // 010
const EXEC = 4;     // 100

$user = READ | WRITE;                         // combine flags: 011 = 3
echo "can read?  " . (($user & READ) ? 'yes' : 'no') . "
";
echo "can exec?  " . (($user & EXEC) ? 'yes' : 'no') . "
";
$user |= EXEC;                                // grant exec
$user &= ~WRITE;                              // revoke write
echo "now mask = $user
";                    // 101 = 5

// Enumerate every pizza: loop the mask from 0 to 2^n - 1.
$toppings = ['Paneer', 'Onion', 'Capsicum'];
$n = count($toppings);
for ($mask = 0; $mask < (1 << $n); $mask++) {
    $chosen = [];
    for ($i = 0; $i < $n; $i++) {
        if ($mask & (1 << $i)) $chosen[] = $toppings[$i];
    }
    echo $mask . ": " . ($chosen ? implode(' + ', $chosen) : '(plain)') . "
";
}

JavaScript

// Permission flags: each is one bit.
const READ = 1;     // 001
const WRITE = 2;    // 010
const EXEC = 4;     // 100

let user = READ | WRITE;                      // combine flags: 011 = 3
console.log("can read?  " + ((user & READ) ? 'yes' : 'no'));
console.log("can exec?  " + ((user & EXEC) ? 'yes' : 'no'));
user |= EXEC;                                 // grant exec
user &= ~WRITE;                               // revoke write
console.log("now mask = " + user);            // 101 = 5

// Enumerate every pizza: loop the mask from 0 to 2^n - 1.
const toppings = ['Paneer', 'Onion', 'Capsicum'];
const n = toppings.length;
for (let mask = 0; mask < (1 << n); mask++) {
  const chosen = [];
  for (let i = 0; i < n; i++) {
    if (mask & (1 << i)) chosen.push(toppings[i]);
  }
  console.log(mask + ": " + (chosen.length ? chosen.join(' + ') : '(plain)'));
}

Java

import java.util.*;

public class Main {
    // Permission flags: each is one bit.
    static final int READ = 1;     // 001
    static final int WRITE = 2;    // 010
    static final int EXEC = 4;     // 100

    public static void main(String[] args) {
        int user = READ | WRITE;                      // combine flags: 011 = 3
        System.out.println("can read?  " + ((user & READ) != 0 ? "yes" : "no"));
        System.out.println("can exec?  " + ((user & EXEC) != 0 ? "yes" : "no"));
        user |= EXEC;                                 // grant exec
        user &= ~WRITE;                               // revoke write
        System.out.println("now mask = " + user);     // 101 = 5

        // Enumerate every pizza: loop the mask from 0 to 2^n - 1.
        String[] toppings = {"Paneer", "Onion", "Capsicum"};
        int n = toppings.length;
        for (int mask = 0; mask < (1 << n); mask++) {
            List<String> chosen = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                if ((mask & (1 << i)) != 0) chosen.add(toppings[i]);
            }
            System.out.println(mask + ": " + (chosen.isEmpty() ? "(plain)" : String.join(" + ", chosen)));
        }
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

// Permission flags: each is one bit.
const (
	Read  = 1 // 001
	Write = 2 // 010
	Exec  = 4 // 100
)

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

func main() {
	user := Read | Write // combine flags: 011 = 3
	fmt.Println("can read?  " + yesNo(user&Read != 0))
	fmt.Println("can exec?  " + yesNo(user&Exec != 0))
	user |= Exec                    // grant exec
	user &^= Write                  // revoke write
	fmt.Println("now mask =", user) // 101 = 5

	// Enumerate every pizza: loop the mask from 0 to 2^n - 1.
	toppings := []string{"Paneer", "Onion", "Capsicum"}
	n := len(toppings)
	for mask := 0; mask < (1 << n); mask++ {
		var chosen []string
		for i := 0; i < n; i++ {
			if mask&(1<<i) != 0 {
				chosen = append(chosen, toppings[i])
			}
		}
		label := "(plain)"
		if len(chosen) > 0 {
			label = strings.Join(chosen, " + ")
		}
		fmt.Printf("%d: %s\n", mask, label)
	}
}

Time: O(2^n × n) to list all subsets · Extra space: O(1) per mask. Checking or combining masks is O(1), but there are 2^n masks of n items, so enumeration only works for small n (up to about 20).

Watch out for

  • Using more than 31 or 63 items in one integer. Each bit needs a place, and JS only has 32 bits for shift and bitwise operations.
  • Forgetting that mask 0 is the empty set and a valid combination.
  • Mixing up flags with plain numbers. Flag values must be distinct powers of two (1, 2, 4, 8) or they overlap.

Quick check

  1. With 4 items, how many different masks (subsets) exist?
    • 4
    • 8
    • 16
  2. Which expression tests whether item i is in the mask?
    • mask | (1 << i)
    • mask & (1 << i)
    • mask ^ i
  3. Why must flag values be powers of two?
    • So each flag owns a different bit and flags never overlap
    • To make them bigger
    • Because PHP requires it