Bitwise Operators Resource - aloalgo

Bitwise Operators

Bitwise operators work directly on the binary representation of numbers. They're essential for bit manipulation problems and can provide elegant, efficient solutions to certain problems.

The Six Bitwise Operators

AND (&)

Returns 1 only if both bits are 1. Useful for checking if a bit is set or clearing bits.

OR (|)

Returns 1 if at least one bit is 1. Useful for setting bits.

XOR (^)

Returns 1 if bits are different. XOR has special properties: a ^ a = 0, a ^ 0 = a, and it's commutative and associative.

NOT (~)

Flips all bits. In Python, ~n = -(n+1) due to two's complement representation.

Left Shift (<<)

Shifts bits left, filling with zeros. Equivalent to multiplying by 2^n.

Right Shift (>>)

Shifts bits right. Equivalent to integer division by 2^n.

Common Bit Manipulation Techniques

Check, Set, Clear, Toggle Bits

Count Set Bits (Population Count)

Get Lowest Set Bit

Check if Power of Two

Bit Masking

XOR Tricks

Summary

  • & (AND): Check/clear bits, test if even
  • | (OR): Set bits
  • ^ (XOR): Toggle bits, find unique elements
  • ~ (NOT): Flip all bits
  • << (Left shift): Multiply by 2, create masks
  • >> (Right shift): Divide by 2, extract bits
  • n & (n-1): Clear lowest set bit, check power of 2
  • n & (-n): Isolate lowest set bit
Was this helpful?
© 2026 aloalgo. All rights reserved.