Programming · intermediate

Bitwise operators

Bitwise operators transform integer bit patterns position by position: AND keeps shared set bits, OR combines set bits, XOR keeps differing bits, NOT complements bits, and shifts move positions. Exact width, signedness, and shift behavior are language- and type-specific.

Why it matters

Bit operations compactly represent flags, extract protocol fields, align storage, manipulate permissions, and implement low-level algorithms. Explicit masks make the intended bit field reviewable.

Mental model

How to reason about bitwise operators

Line up fixed-width patterns vertically and apply a truth rule independently in each column. A mask marks the positions to inspect or change; the surrounding type defines what exists beyond the displayed width.

Analogy

A bit mask is a stencil placed over a row of switches: AND reveals selected switches, OR forces selected switches on, and XOR flips the selected switches.

Examples

See the boundary, not just the happy path

Worked example · Test a flag

permissions & 0b0100 != 0

AND clears every position except the selected flag. A nonzero result means that bit was set; this assumes permissions is an integer type with the intended bit layout.

Worked example · Clear a flag

flags = flags & ~0b0010

NOT constructs a mask with the target position cleared and other in-width positions set, then AND clears only that flag. In arbitrary-width or signed languages, type width must be understood.

Useful contrast · Logical operators combine truth values

ready && authorized

Logical AND asks whether two conditions are true and often short-circuits. Bitwise AND computes every result bit and generally evaluates both operands.

Common mistakes

Misconceptions to remove early

Assuming shifts behave identically in every language

Rules differ for signed values, oversized shift counts, overflow, and whether right shift is arithmetic or logical. Use an explicit unsigned width when the bit pattern matters.

Using addition to combine flags

Addition can carry into neighboring bits and repeated flags change the result. Bitwise OR expresses set membership and is idempotent for an already-set flag.

Quick check

Can you predict the result?

1. What is 0b1100 AND 0b1010?
  • 0b1000
  • 0b1110
  • 0b0110
Answer: 0b1000
2. Why is an unsigned fixed-width type often preferable for portable bit manipulation?
Answer: It makes the available positions and shift/overflow interpretation more explicit and avoids signed-representation surprises.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster