Common tricks and patterns every developer should know
Given an integer x and a bit position n (0-indexed from LSB):
Returns 1 if bit n is 1, 0 otherwise
Sets bit n to 1 regardless of current value
Sets bit n to 0
Flips bit n: 0→1, 1→0
Sets all bits where M has a 1
Clears all bits where M has a 1
Flips all bits where M has a 1
Isolates the rightmost 1 bit
Any power of 2 has exactly one bit set. Subtracting 1 flips all lower bits, so AND gives zero. Works for 1, 2, 4, 8, 16…
Each iteration clears the lowest set bit. Runs in O(number of set bits) — efficient for sparse numbers.
XOR swap. Works because x ^ x = 0 and XOR is associative. Gotcha Does not work if a and b reference the same memory location (both become 0).
The MSB is the sign bit. If a and b have different signs, XOR yields a negative result. Faster than (a < 0) != (b < 0).
Also known as "branchless abs". mask is all 1s for negative x, all 0s for positive. Works for 32-bit signed integers.
Propagates the highest set bit to all lower bits, then adds 1. Returns 0 for x=0 (watch out). 32-bit
n=0 gives the least significant byte, n=3 gives the most significant (on a 32-bit word).
All these examples assume two's complement representation, which is what most modern hardware and all mainstream languages (C, C++, Java, Rust, Go, Python) use. In two's complement:
~x + 1-1 is all bits set: 0xFFFFFFFF