DevLab
Numbers

Bitwise Operations for Web Developers

A practical guide to AND, OR, XOR, NOT, and bit shifting — with real use cases like feature flags, permissions, and colour manipulation.

Why Bitwise Operations Matter

Bitwise operations manipulate individual bits in a number. They are fast — a single CPU cycle — and memory-efficient: you can store 32 boolean flags in a single 32-bit integer instead of 32 separate variables. If you have ever used Unix permissions, React reconciliation flags, or feature toggles in a database, you have used bitwise operations.

AND (&) — Check If a Bit Is Set

AND compares each bit pair and returns 1 only if both bits are 1. Use AND to check whether a specific flag is enabled.

const READ  = 0b001  // 1
const WRITE = 0b010  // 2
const EXEC  = 0b100  // 4

const perms = READ | WRITE  // 0b011 = 3

// Check if WRITE is set
if (perms & WRITE) {
  console.log('Write is enabled')  // ✓
}
if (perms & EXEC) {
  console.log('Exec is enabled')   // not reached
}

OR (|) — Set a Bit

OR returns 1 if either bit is 1. Use OR to enable a flag without affecting other flags.

let perms = READ          // 0b001
perms = perms | WRITE     // 0b011 — WRITE added
perms = perms | EXEC      // 0b111 — EXEC added

XOR (^) — Toggle a Bit

XOR returns 1 if the bits are different. Use XOR to toggle a flag: if it is on, turn it off; if it is off, turn it on.

let flags = 0b101
flags = flags ^ 0b001  // 0b100 — first bit toggled off
flags = flags ^ 0b001  // 0b101 — first bit toggled back on

XOR is also used in simple checksums, swap-without-temp-variable tricks, and certain encryption algorithms.

NOT (~) — Invert All Bits

NOT flips every bit. In JavaScript (32-bit signed integers), ~n equals -(n + 1). A common trick: ~-1 equals 0 (falsy), so if (~str.indexOf('x')) was used before str.includes() existed. Avoid this pattern in modern code — use includes() instead.

Bit Shifting (<<, >>)

Left shift (<<) moves bits left, effectively multiplying by powers of 2. Right shift (>>) moves bits right, dividing by powers of 2 (rounding down).

1 << 0   // 1   (2⁰)
1 << 3   // 8   (2³)
1 << 10  // 1024 (2¹⁰)

255 >> 4  // 15  (integer division by 16)

Shift is commonly used to extract colour channels from a packed integer: (0xFF6B4A >> 16) & 0xFF extracts the red channel (255).

Real-World Use Cases

  • Feature flags — Store multiple toggles in one database column: if (user.features & BETA_ACCESS)
  • Permissions — Unix-style rwx bits: read=4, write=2, execute=1
  • Packed colours — RGB in a single integer: (r << 16) | (g << 8) | b
  • Hash functions — All hash algorithms use extensive bit manipulation internally

Frequently Asked Questions

When are bitwise operations actually useful in application development?

The most common use cases are: feature flags (store 32 boolean settings in a single integer using bit masking), permission systems (Unix file permissions use bitwise OR to combine read/write/execute), color manipulation (extracting RGB channels from a 24-bit color value with shifts and masks), and performance-critical code where bitwise tricks replace branching (like checking if a number is even with n & 1 instead of n % 2). In web development, they appear less often but still matter in canvas manipulation, WebGL, and binary protocol parsing.

What is the difference between logical AND (&&) and bitwise AND (&)?

Logical AND (&&) evaluates two boolean expressions and short-circuits — if the left side is false, the right side is never evaluated. It returns a boolean. Bitwise AND (&) operates on every bit of two integers simultaneously, comparing each bit position and returning 1 only where both operands have 1. For example, 12 & 10 compares 1100 and 1010 bit by bit, producing 1000 (8). They solve fundamentally different problems: && for control flow, & for bit manipulation.

Why does left-shifting by 1 double a number?

Left-shifting moves every bit one position to the left and fills the vacated rightmost bit with 0. In binary positional notation, each position represents a power of 2, so shifting left multiplies by 2 — just like appending a 0 in decimal multiplies by 10. The number 5 (101 in binary) becomes 10 (1010) after a left shift by 1. This works for unsigned integers; for signed integers, shifting into the sign bit causes overflow and implementation-defined behavior in C/C++.

Practice with these tools

More Learning Topics

RegexRegex Basics: A Complete Beginner's GuideRegexRegex Special Characters: Complete ReferenceRegexRegex Groups and Captures ExplainedRegexRegex Quantifiers: Complete GuideCSSCSS Selectors: The Complete GuideCSSCSS Specificity: Why Your Styles Aren't ApplyingJSONJSONPath Syntax: Query JSON Like XPathTimeUnix Timestamps ExplainedEncodingBase64 Encoding ExplainedEncodingJWT Structure and How It WorksEncodingJWT vs Session Tokens: Which Should You Use?EncodingJWT Refresh Tokens ExplainedCryptoHash Functions Explained: MD5, SHA-256, and When to Use EachEncodingURL Encoding Explained: What %20 Actually MeansJSONJSON Schema Explained: Validate Your JSON DataJSONJSON vs YAML: Which Should You Use?JSONJSON.stringify and JSON.parse: Edge Cases You Should KnowRegexRegex Lookahead and Lookbehind: Match Without ConsumingRegexRegex for Email Validation: The Right ApproachCSSThe CSS Box Model: margin, padding, border, and contentCSSFlexbox vs CSS Grid: When to Use EachCSSCSS Custom Properties (Variables) ExplainedTimeISO 8601 Explained: The Right Way to Format DatesTimeUnix Timestamps vs ISO 8601: Which to Use in Your API?EncodingUTF-8 Explained: How Computers Store TextTextCORS Explained: Why Your API Call is BlockedTextHTTP Status Codes: A Practical Developer GuideRegexNamed Capture Groups in Regex: Clean ExtractionsColorsColor Spaces Explained: RGB, HSL, HEX, and BeyondColorsColor Contrast for Developers: WCAG Rules and How to CheckNumbersNumber Bases Explained: Binary, Octal, Decimal, and HexHTMLHTML Semantic Elements: A Complete ReferenceTextText Encoding for Developers: ASCII, UTF-8, and UnicodeRegexWhat is Regex? Complete Guide for DevelopersJSONJSON Format Explained: Structure, Syntax, and Common ErrorsEncodingHow JWT Works: Header, Payload, Signature DecodedHTMLHow to Convert Any Website to Markdown (for LLMs, RAG & Docs)TextPreparing Website Content for RAG: Clean Markdown Pipelines