Workspace Bit Manipulation
0d
DSA topics

Bit Manipulation

Binary digits encode switches, powers of two and membership in a small set. Bit operations can inspect or change several switches at once.

Picture the idea

A bank of light switches records several yes/no answers. A mask selects exactly the switches you want to inspect.

When to use it

Use a fixed-width integer for flags, parity, power-of-two tests or repeated-pair cancellation.

How it works

For positive n, n−1 flips the lowest set bit and all lower zeroes. AND with n clears that set bit, so repeatedly applying this step counts ones.

  • Test bit k with a mask.
  • Set, clear or toggle a bit.
  • Shift within a defined width.
  • Cancel equal pairs with XOR.

For a fixed machine word, primitive bit operations are O(1). Clearing one set bit per iteration takes O(number of set bits).

Watch for this mistake

Zero passes n & (n−1) == 0; a power-of-two test also requires n > 0.

State integer width and signedness when shifting or complementing values.

Practice in the lab

Related learning