Bitwise Operations Guide

A thorough walkthrough of AND, OR, XOR, NOT, left shift, and right shift — with binary examples, truth tables, and real-world applications for programmers and students.

Developer workspace with dual monitors for learning bitwise computing
What Is a Bitwise Operation? AND OR XOR NOT / Two's Complement Left & Right Shift Real-World Applications FAQ

What Is a Bitwise Operation?

A bitwise operation is an operation that acts on the individual bits — the 0s and 1s — of a binary number. Unlike arithmetic operations like addition or multiplication, which treat a number as a single value, bitwise operations let you manipulate each bit independently. This gives programmers fine-grained control over data at the lowest level.

In modern computing, every piece of data is ultimately a sequence of bits. Bitwise operations are the tools that work directly on these bits, and they are central to:

There are six fundamental bitwise operations: AND, OR, XOR, NOT, left shift, and right shift. Each serves a distinct purpose, and together they form a complete toolkit for bit-level manipulation. Below we cover each one in detail with truth tables, worked binary examples, and the common programming idioms that use them.

Bitwise AND (&)

The AND operation compares two bits and returns 1 only when both bits are 1. In all other cases, it returns 0. This is the bit-level equivalent of the logical AND, applied to every corresponding pair of bits in two numbers.

Truth Table

Bit ABit BA AND B
000
010
100
111

Binary Example

AND: 13 (1101) & 11 (1011)
1101   (13)
1011   (11)
---- &
1001   (9)
Decimal: 13 & 11 = 9 | Hex: 0xD & 0xB = 0x9

Real-World Use: Masking

The most common use of AND is masking — using a mask value to extract or clear specific bits from a number. A mask is a value where the bits you want to keep are set to 1 and the bits you want to clear are set to 0.

Extract the low byte: 0xABCD & 0x00FF
0xABCD  =  1010 1011 1100 1101
0x00FF  =  0000 0000 1111 1111
------------------- &
0x00CD  =  0000 0000 1100 1101
Only the low byte (0xCD) survives — the high byte is zeroed out.

You can also use AND to test whether a specific bit is set. The pattern value & (1 << N) returns nonzero exactly when bit N is 1. This is the standard check across virtually every programming language, from C to JavaScript to Python.

AND Masking Idiom

To check if bit 3 is set in a value: if (value & 0x08) { /* bit 3 is set */ }. The mask 0x08 has a single 1 at bit position 3. Use our bitwise calculator to experiment with different masks interactively.

Bitwise OR (|)

The OR operation returns 1 when at least one of the two bits is 1. It returns 0 only when both bits are 0. OR is used to set specific bits to 1 without disturbing other bits in the value.

Truth Table

Bit ABit BA OR B
000
011
101
111

Binary Example

OR: 12 (1100) | 3 (0011)
1100   (12)
0011   (3)
---- |
1111   (15)
Decimal: 12 | 3 = 15 | Hex: 0xC | 0x3 = 0xF

Real-World Use: Setting Flags

OR is the standard way to enable individual bits in a bitfield without changing other bits. Many operating systems and APIs use bitfields for flags — for example, Linux's open() system call takes a flags argument where each bit represents a different option (O_RDONLY, O_WRONLY, O_CREAT, etc.).

Set bits 2 and 5 in a flags register
flags  =  0000 0000
flags |= (1 << 2)    flags = 0000 0100
flags |= (1 << 5)    flags = 0010 0100
Each OR operation sets exactly one bit: flags = 0x24 (36 decimal)

OR Setting Idiom

To set bit N: value |= 1 << N;. This pattern is used across file permission flags, network socket options, and hardware register configuration. Use our programming calculator to see the binary representation as you set individual bits.

Bitwise XOR (^)

The XOR (exclusive OR) operation returns 1 when the two bits differ — one is 0 and the other is 1. When both bits are the same (both 0 or both 1), XOR returns 0. This seemingly simple operation has remarkable properties that make it invaluable in cryptography, error detection, and algorithm design.

Truth Table

Bit ABit BA XOR B
000
011
101
110

Binary Example

XOR: 10 (1010) ^ 6 (0110)
1010   (10)
0110   (6)
---- ^
1100   (12)
Decimal: 10 ^ 6 = 12 | Hex: 0xA ^ 0x6 = 0xC

The XOR Swap Trick

A classic demonstration of XOR's power is swapping two variables without using a temporary variable. This works because XOR is its own inverse: a ^ b ^ b = a.

XOR Swap: a=5, b=3
a = a ^ b    a = 5 ^ 3 = 6
b = a ^ b    b = 6 ^ 3 = 5
a = a ^ b    a = 6 ^ 5 = 3
Result: a=3, b=5 ✓

Real-World Use: Cryptography and Toggling

XOR is the foundation of the one-time pad cipher, which is provably unbreakable when used correctly. The principle is simple: plaintext XOR key = ciphertext, and ciphertext XOR key = plaintext. Many modern stream ciphers (like ChaCha20) use XOR as their core mixing operation. XOR is also used for toggling bits: flags ^= 0x80 flips bit 7, turning it from 0 to 1 or from 1 to 0 on each call.

Bitwise NOT (~) and Two's Complement

The NOT operation is unary — it operates on a single value. It flips every bit: 0 becomes 1, and 1 becomes 0. This is also called the one's complement. However, because modern computers use two's complement to represent signed integers, the result of NOT is closely tied to how negative numbers are stored.

Truth Table

BitNOT Bit
01
10

Binary Example

NOT: ~5 (8-bit view)
5  =  0000 0101
---- ~
~5 = 1111 1010
In two's complement: 1111 1010 = -6, so ~5 = -6

Understanding Two's Complement

In two's complement, a negative number is created by taking the positive number's bits, flipping them (NOT), and adding 1. This means:

NOT in Practice

NOT is commonly used in combination with AND to clear specific bits. The pattern value & ~mask clears all bits that are set in the mask, while leaving other bits unchanged. For example, value & ~0x0F clears the low 4 bits. Try it on our bitwise calculator and watch the binary representation update in real time.

Left Shift (<<) and Right Shift (>>)

Shift operations move all bits in a value left or right by a specified number of positions. They provide a very fast way to multiply or divide by powers of two and are used heavily in bitfield extraction, building masks, and serialization.

Left Shift (<<)

A left shift moves every bit to the left by N positions. The leftmost N bits are discarded (they "fall off"), and N zeros are added on the right side. Each left shift by 1 position multiplies the value by 2.

Left Shift: 3 << 4
3       =  0000 0011
3 << 1  =  0000 0110   (6, same as 3 × 2)
3 << 2  =  0000 1100   (12, same as 3 × 4)
3 << 3  =  0001 1000   (24, same as 3 × 8)
3 << 4  =  0011 0000   (48, same as 3 × 16)
Decimal: 3 << 4 = 48 | Formula: n << k = n × 2k

Shift Overflow Warning

In JavaScript and most languages, left shift beyond the word size wraps around. For 32-bit integers, 1 << 31 works fine, but 1 << 32 returns 0 because only the low 5 bits of the shift count are used (32 mod 32 = 0). Our 64-bit programmer calculator uses BigInt to avoid this limitation.

Right Shift (>>)

A right shift moves every bit to the right by N positions. The rightmost N bits are discarded, and the sign bit is propagated on the left (this is called arithmetic shift or sign-propagating shift). Each right shift by 1 position performs integer division by 2, truncating toward negative infinity.

Right Shift: 64 >> 3
64        =  0100 0000
64 >> 1  =  0010 0000   (32, same as 64 / 2)
64 >> 2  =  0001 0000   (16, same as 64 / 4)
64 >> 3  =  0000 1000   (8, same as 64 / 8)
Decimal: 64 >> 3 = 8 | Formula: n >> k = floor(n / 2k)
Right Shift with Negative: -16 >> 2
-16      =  1111 0000 (8-bit two's complement)
-16 >> 1  =  1111 1000 (-8)
-16 >> 2  =  1111 1100 (-4)
Sign bit propagates: -16 >> 2 = -4

Unsigned Right Shift (>>>)

Some languages (JavaScript, Java, C#) also provide an unsigned right shift (>>>) that fills with zeros from the left instead of propagating the sign bit. This treats the value as unsigned and is useful for working with raw binary data where the sign bit should be treated as a regular data bit.

Real-World Applications of Bitwise Operations

Flag Bitfields

One of the most common uses of bitwise operations is packing multiple boolean flags into a single integer. Instead of using eight separate boolean variables (which take at least one byte each), you can store eight flags in one byte. Each bit represents one flag.

File Permission Flags (Unix-style)
#define READ    (1 << 0)  // 0001  = 1
#define WRITE   (1 << 1)  // 0010  = 2
#define EXECUTE (1 << 2)  // 0100  = 4

// Set read and execute: permissions = READ | EXECUTE = 5
// Check write: if (permissions & WRITE) false (bit 1 is 0)

Bitmasking in Network Protocols

Network packet headers frequently pack multiple fields into a single word to save bandwidth. For example, the TCP header's data offset field occupies 4 bits, and the flags field occupies 9 bits, all packed into the same 16-bit word. Bitwise operations are necessary to extract and set these fields.

Similarly, IP addresses and subnet masks use AND operations for subnet routing. The router computes destination_IP & subnet_mask to determine which network a packet belongs to — a bitwise AND test that happens at wire speed in hardware.

Fast Arithmetic

On most CPUs, a bit shift executes in a single clock cycle, while multiplication can take 3-10 cycles. Compilers routinely optimize x * 16 to x << 4 and x / 8 to x >> 3 when the operand is a power of two. In performance-critical code, writing shifts explicitly signals intent and guarantees the fast path.

Shift vs Multiply Performance
// Fast path (1 cycle):
int result = pixel_index << 2;   // multiply by 4

// Slower path (3-10 cycles):
int result = pixel_index * 4;

Color Channel Extraction in Graphics

In computer graphics, a 32-bit color value typically packs four 8-bit channels into one integer: alpha (bits 24-31), red (bits 16-23), green (bits 8-15), and blue (bits 0-7). Bitwise operations extract each channel.

Extract RGBA Channels
color = 0xAABBCCDD   // ARGB format
alpha = (color >> 24) & 0xFF   // 0xAA
red   = (color >> 16) & 0xFF   // 0xBB
green = (color >>  8) & 0xFF   // 0xCC
blue  = (color >>  0) & 0xFF   // 0xDD

Bitsets and Bloom Filters

A bitset (or bit array) is a compact data structure that stores a set of flags using one bit per element. It is much more memory-efficient than an array of booleans. For example, a bitset tracking which integers from 0 to 1,000,000 have been "seen" requires only 125 KB (1 million bits) instead of 4 MB (1 million 32-bit integers).

Bloom filters extend this idea with multiple hash functions and probabilistic membership testing. They use bitwise operations extensively and are used in databases, web caches, and network routing to quickly determine whether an element might be in a set without expensive lookups.

Try These Operations Live

Enter any two numbers in our interactive bitwise calculator and see the binary, decimal, and hex results update instantly. The 32-bit visualization shows you exactly which bits change in each operation.

Frequently Asked Questions About Bitwise Operations

What is a bitwise operation?

A bitwise operation is an operation that acts on the individual bits (0s and 1s) of a binary number. Unlike arithmetic operations that treat numbers as whole values, bitwise operations work at the bit level. The six fundamental bitwise operations are AND, OR, XOR, NOT, left shift, and right shift. They are essential in systems programming, embedded development, cryptography, and performance-critical code where direct control over individual bits is needed.

How does bitwise AND work?

Bitwise AND (&) returns 1 only when both corresponding bits are 1, and 0 otherwise. For example, 5 (0101) AND 3 (0011) = 1 (0001). AND is commonly used for masking — extracting or clearing specific bits while leaving others unchanged. To check if bit N is set in a value, use (value & (1 << N)) !== 0.

How does bitwise OR work?

Bitwise OR (|) returns 1 when at least one of the two corresponding bits is 1, and 0 only when both are 0. For example, 5 (0101) OR 3 (0011) = 7 (0111). OR is used for setting specific bits in a value. For instance, flags |= 0x04 sets bit 2 without modifying other bits, making it ideal for enabling features stored in bitfields.

What is bitwise XOR used for?

Bitwise XOR (^) returns 1 when the two corresponding bits differ, and 0 when they are the same. For example, 5 (0101) XOR 3 (0011) = 6 (0110). XOR has a unique property: applying it twice with the same value restores the original, making it fundamental in cryptography. Common uses include toggling flags (flags ^= 0x80), swapping variables without a temporary, and parity calculations in error detection.

How do bit shifts work and when would I use them?

Left shift (<<) moves all bits to the left, filling with zeros from the right, effectively multiplying by 2^N. Right shift (>>) moves bits right, dropping the least significant bits, effectively performing integer division by 2^N. For example, 1 << 3 = 8 (equivalent to 2^3), and 16 >> 2 = 4. Shifts are much faster than multiplication or division on most CPUs and are commonly used for power-of-two calculations, bit extraction, and building bitmasks.

What is two's complement and how does NOT work with signed numbers?

Two's complement is the standard way computers represent signed integers. In an 8-bit system, -1 is represented as 11111111 (all bits set). Bitwise NOT (~) flips every bit: each 0 becomes 1 and each 1 becomes 0. In two's complement, ~x equals -x - 1. For example, ~5 = -6, and ~0 = -1 (which is 0xFFFFFFFF in a 32-bit system). Understanding this is critical when working with signed vs unsigned interpretations of bitwise NOT results.

What are practical applications of bitwise operations in programming?

Bitwise operations have many real-world uses: flag bitfields where each bit represents a boolean option (e.g., file permission bits rwx), bitmasking to extract specific fields from packed data (common in network protocols and binary file formats), fast power-of-two arithmetic using shifts, implementing bitsets and bloom filters, CRC checksums, swapping variables without temporary storage, and low-level hardware register manipulation in embedded systems. JavaScript's own parseInt uses bitwise tricks internally.

Related Tools

Bitwise Calculator →

AND, OR, XOR, NOT, shifts

Bitwise Guide →

Complete operations reference

Hex to ASCII →

Decode hex strings

SHA256 Generator →

Compute hashes