AlgoTales · Roadmap

AND, OR, XOR, NOT

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

Where you will meet this in real life

Inside a computer, numbers are rows of on or off switches called bits. AND, OR, XOR and NOT combine those switches directly. They let one small number hold many yes or no answers, and make checks very fast and compact.

Practical use cases

  • Web app: User permissions in one number. An admin panel gives each user permissions: read is 1, write is 2, delete is 4, publish is 8. A user with read and write is stored as 3 in one database column. Checking permission is a single AND, and adding or removing one is a single OR or flip, with no extra tables.
  • Web app: Feature flags per customer. A SaaS app turns features like dark mode, export and API access on for some plans only. Each feature is one bit of an integer saved with the account. Loading the account loads all flags together and the code asks a quick AND question.
  • System: Finding the odd one out. XOR of two equal numbers is zero, so XOR-ing a list where everything appears twice except one leaves only the single one. Network and storage tools use similar switch tricks for checksums and parity, so a damaged message or a failed disk can be spotted and often repaired.

The story: The Switchboard in Grandpa's House

Grandpa's old house had a board with eight light switches in a row. Mira discovered something amazing: by flipping them in different patterns, Grandpa could send secret signals to neighbours across the street.

One night the neighbour had a switchboard too, and Mira wondered: "What if I wanted lights that are on in both boards? Or on in either? Or on in exactly one?" She was inventing AND, OR and XOR without knowing it.

Every computer is secretly a giant switchboard. A number is just switches that are on (1) or off (0). Once you can flip and compare switches directly, you can pack many yes/no answers into one tiny number, which is exactly how permission flags and feature toggles work.

How to spot this problem, and where you need it

You have many yes or no settings per record and your database is cluttered with columns or rows for each one, or you need a quick check on whether something has a feature.

Signs you need it

  • A table has columns such as can_read, can_write, can_delete, is_admin, each holding just 0 or 1.
  • The problem talks about states, flags, masks, or combinations of on and off options for one item.
  • You need to find the unique number among duplicates without using extra memory.

Where to use it in a project

  • Role and permission systems, such as file access or admin screens, where every user has a set of allowed actions.
  • Notification preferences, plan features and onboarding checklists stored together with the account.

The solution

Give every option its own bit, a number that is a power of 2: 1, 2, 4, 8 and so on. Store the combination as one integer by joining the chosen bits with OR. Ask whether an option is present with AND: if the result is not zero, it is on. Remove an option by AND with the opposite of its bit. Use XOR when you need to know where two values differ.

Payoff: Before: eight permission columns and eight conditions. After: one integer column and one-line checks like (perms & 4) !== 0.

Explain it like I am 8

A bit is a light switch: ON (1) or OFF (0). AND asks "are BOTH on?". OR asks "is AT LEAST ONE on?". XOR asks "are they DIFFERENT?". NOT flips every switch to the opposite.

How it works, step by step

  1. AND (&): result is 1 only if both bits are 1. Great for checking a switch: flags & 4.
  2. OR (|): result is 1 if either bit is 1. Great for turning on a switch: flags | 4.
  3. XOR (^): result is 1 only when the bits differ. Great for toggling, and a famous trick: a number XOR itself is 0.
  4. Shifts (<<, >>) slide all switches left or right. Shifting left by one doubles the number.

The code in four languages

PHP

<?php
const READ = 1, WRITE = 2, DELETE = 4;

$perms = READ | WRITE;                    // turn on two switches   -> 0b011
$canWrite  = ($perms & WRITE) !== 0;      // check a switch         -> true
$perms ^= DELETE;                         // toggle a switch        -> now on
$perms &= ~WRITE;                         // turn a switch OFF

$n = 7;
$isOdd = ($n & 1) === 1;                  // odd/even in one step

// Find the loner: everything else appears twice
function loner(array $nums): int {
    $x = 0;
    foreach ($nums as $v) $x ^= $v;       // pairs cancel out
    return $x;
}
echo "can write? ", $canWrite ? 'yes' : 'no', "\n";      // yes
echo "perms now: ", decbin($perms), "\n";          // 101 = READ + DELETE
echo "7 is odd? ", $isOdd ? 'yes' : 'no', "\n";       // yes
echo "loner: ", loner([4, 9, 4, 7, 9]), "\n";        // 7

JavaScript

const READ = 1, WRITE = 2, DELETE = 4;

let perms = READ | WRITE;                 // turn on two switches   -> 0b011
const canWrite = (perms & WRITE) !== 0;   // check a switch         -> true
perms ^= DELETE;                          // toggle a switch        -> now on
perms &= ~WRITE;                          // turn a switch OFF

const n = 7;
const isOdd = (n & 1) === 1;              // odd/even in one step

// Find the loner: everything else appears twice
function loner(nums) {
  let x = 0;
  for (const v of nums) x ^= v;           // pairs cancel out
  return x;
}
console.log('can write?', canWrite);                 // true
console.log('perms now:', perms.toString(2));        // 101 = READ + DELETE
console.log('7 is odd?', isOdd);                     // true
console.log('loner:', loner([4, 9, 4, 7, 9]));       // 7

Java

public class Main {
    static final int READ = 1, WRITE = 2, DELETE = 4;

    // Find the loner: everything else appears twice
    static int loner(int[] nums) {
        int x = 0;
        for (int v : nums) x ^= v;            // pairs cancel out
        return x;
    }

    public static void main(String[] args) {
        int perms = READ | WRITE;                    // turn on two switches   -> 0b011
        System.out.println("perms: " + Integer.toBinaryString(perms));                 // 11
        boolean canWrite = (perms & WRITE) != 0;     // check a switch         -> true
        System.out.println("can write? " + canWrite);                                  // true
        perms ^= DELETE;                             // toggle a switch        -> now on
        System.out.println("after toggle: " + Integer.toBinaryString(perms));          // 111
        perms &= ~WRITE;                             // turn a switch OFF
        System.out.println("after clearing write: " + Integer.toBinaryString(perms));  // 101

        int n = 7;
        boolean isOdd = (n & 1) == 1;                // odd/even in one step
        System.out.println(n + " odd? " + isOdd);                                      // true

        System.out.println(loner(new int[]{4, 9, 4, 7, 9}));   // 7
    }
}

Go

package main

import "fmt"

const (
	Read   = 1
	Write  = 2
	Delete = 4
)

// loner finds the one value that is not paired up: everything else appears twice.
func loner(nums []int) int {
	x := 0
	for _, v := range nums {
		x ^= v // pairs cancel out
	}
	return x
}

func main() {
	perms := Read | Write            // turn on two switches   -> 0b011
	fmt.Printf("perms: %b\n", perms) // 11
	canWrite := perms&Write != 0     // check a switch         -> true
	fmt.Println("can write?", canWrite)
	perms ^= Delete                                 // toggle a switch        -> now on
	fmt.Printf("after toggle: %b\n", perms)         // 111
	perms &^= Write                                 // turn a switch OFF (&^ is "and not")
	fmt.Printf("after clearing write: %b\n", perms) // 101

	n := 7
	isOdd := n&1 == 1 // odd/even in one step
	fmt.Println(n, "odd?", isOdd)

	fmt.Println(loner([]int{4, 9, 4, 7, 9})) // 7
}

Time: O(1) per operation · Extra space: O(1). Bit operations are single CPU instructions. Looping over n numbers with XOR is O(n).

Watch out for

  • Mixing up & (bitwise) with && (logical). They look alike but do different jobs.
  • In JavaScript, bitwise operators treat numbers as 32-bit integers, so very large values wrap around.

Quick check

  1. Which operator checks "are the two bits DIFFERENT"?
    • AND
    • OR
    • XOR
  2. You XOR 5, 8, 5, 8, 3 together. What is left?
    • 0
    • 3
    • 8
  3. Shifting a number left by one position…
    • Doubles it
    • Halves it
    • Makes it negative