Bitwise Calculator
AND, OR, XOR, NOT, shifts
About This Calculator
Bitwise operators work directly on the binary representation of integers. They are fundamental in low-level programming, embedded systems, flag manipulation, encryption, and performance optimization. Understanding bitwise operations is essential for anyone working with binary protocols, hardware registers, or systems programming.
Formula
AND (&): 1 only when both bits are 1 — used to mask/check specific bits
OR (|): 1 when either bit is 1 — used to set specific bits
XOR (^): 1 only when bits differ — used to toggle bits or compare
NOT (~): flips all bits; Left shift (<<): multiply by 2; Right shift (>>): divide by 2
Example Calculation
Calculate 13 AND 10 and 13 XOR 10 in binary
- 13 = 1101₂; 10 = 1010₂
- AND: 1101 & 1010 = 1000₂ = 8
- XOR: 1101 ^ 1010 = 0111₂ = 7
13 AND 10 = 8; 13 XOR 10 = 7
Bitwise Operation Truth Table (single bit)
| A | B | AND | OR | XOR | NAND | NOR |
|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 1 | 1 |
| 0 | 1 | 0 | 1 | 1 | 1 | 0 |
| 1 | 0 | 0 | 1 | 1 | 1 | 0 |
| 1 | 1 | 1 | 1 | 0 | 0 | 0 |
Frequently Asked Questions
What are bitwise operations used for in programming?
Common uses: checking if a number is even (n & 1 == 0), toggling feature flags (flags ^= FLAG), isolating bits (n & MASK), fast multiplication/division by powers of 2 (n << 3 = n×8), and setting/clearing specific bits in hardware registers.
What does the left shift operator do?
Left shift (n << k) moves all bits k positions to the left, equivalent to multiplying by 2ᵏ. For example, 3 << 2 = 12 (3 × 4). It's faster than multiplication on many processors. Right shift (>>) divides by 2ᵏ, discarding the remainder.
How does XOR work for swapping variables?
XOR swap: a ^= b; b ^= a; a ^= b; swaps a and b without a temporary variable. It works because x XOR x = 0 and x XOR 0 = x. While elegant, it's slower than a simple swap with a temp variable on modern CPUs with registers.
What is a bitmask?
A bitmask is a bit pattern used with AND, OR, or XOR to selectively read, set, or clear individual bits in an integer. For example, mask = 0b00000100 targets bit 2. n & mask checks if bit 2 is set; n | mask sets bit 2; n & ~mask clears bit 2.