Bitwise AND Operation Basics

Learn how the bitwise AND (&) operator works. AND returns 1 only when both corresponding bits are 1. Essential for masking, filtering, and checking flags.

AND Operations

Detailed Explanation

Understanding Bitwise AND (&)

The AND operator compares each pair of corresponding bits from two operands. The result bit is 1 only when both input bits are 1; otherwise the result is 0.

Truth Table

A | B | A & B
--|---|------
0 | 0 |   0
0 | 1 |   0
1 | 0 |   0
1 | 1 |   1

Worked Example

Let's compute 42 & 15:

  42  = 00101010
& 15  = 00001111
──────────────────
  10  = 00001010

Only the bits where both operands have a 1 survive in the result. The upper 4 bits of 42 (0010) are cleared because the corresponding bits in 15 are 0.

Why AND Is Fundamental

AND is the most commonly used bitwise operation because it enables masking — the ability to extract or zero out specific bits from a value. Any bit ANDed with 1 keeps its original value; any bit ANDed with 0 becomes 0. This property makes AND indispensable in:

  • Extracting fields from packed data structures
  • Clearing specific flag bits while preserving others
  • Testing whether a particular bit is set
  • Implementing modulo by powers of 2 (e.g., n & 0x0F is equivalent to n % 16)

Performance Note

AND operates in a single CPU cycle on virtually all processors, making it far faster than equivalent arithmetic operations like modulo.

Use Case

Network engineers use AND to apply subnet masks to IP addresses. For example, ANDing an IP address 192.168.1.100 (0xC0A80164) with a /24 subnet mask 255.255.255.0 (0xFFFFFF00) yields the network address 192.168.1.0 (0xC0A80100). This is how routers determine which network a packet belongs to.

Try It — Bitwise Calculator

Open full tool