bitlvl
EN

Bitwise tricks cheat sheet

Every idiom here works in C, Go, Rust, Java and JavaScript (32-bit) with the same operators; Python too, with unbounded integers.

Fits on one A4 / Letter page in portrait; use “Save as PDF” in the print dialog to keep a copy.

Operators

a & bAND: 1 where both are 1
a | bOR: 1 where either is 1
a ^ bXOR: 1 where they differ
~aNOT: flip all bits (= −a − 1 in two's complement)
a << nshift left: × 2ⁿ
a >> nshift right: ÷ 2ⁿ, rounds toward −∞ for signed (arithmetic)
a >>> nlogical right shift (JS, Java); unsigned types elsewhere

Single bits (bit n, 0 = lowest)

x & (1 << n)test: non-zero if set
(x >> n) & 1get bit as 0 or 1
x | (1 << n)set
x & ~(1 << n)clear
x ^ (1 << n)toggle
(x & ~(1 << n)) | (b << n)set bit n to b

Masks and fields

(1 << n) - 1mask of the low n bits
((1 << w) - 1) << lomask of w bits starting at lo
(x >> lo) & ((1 << w) - 1)extract a w-bit field at lo
(x & ~m) | ((v << lo) & m)insert v into field with mask m
(x & FLAGS) == FLAGSall flags set
x & FLAGSany flag set

Lowest / highest bit

x & -xisolate lowest set bit
x & (x - 1)clear lowest set bit
x | (x + 1)set lowest clear bit
x & (x + 1)clear trailing 1s
x | (x - 1)set trailing 0s
ctz(x) = log₂(x & -x)index of lowest set bit (__builtin_ctz, bits.TrailingZeros)
31 - clz(x)index of highest set bit = ⌊log₂ x⌋

Tests

x && !(x & (x - 1))is a power of two
(x & 1) == 0is even
(x ^ y) < 0opposite signs (signed)
(x & (a - 1)) == 0aligned to a (a = 2ⁿ)
x == (x & 0xFF)fits in a byte

Arithmetic

(x + a - 1) & -around up to multiple of a (a = 2ⁿ)
x & -around down to multiple of a
x & (a - 1)x mod a (a = 2ⁿ, x ≥ 0)
(x + y) >> 1average (may overflow); (x & y) + ((x ^ y) >> 1) does not
x ^= y; y ^= x; x ^= yswap without a temporary (slower than a temp; a curiosity)
(x ^ (x >> 31)) - (x >> 31)absolute value, 32-bit signed
x ^ (x >> 1)binary → Gray code

Counting and reversing

while (x) { x &= x - 1; n++; }popcount (Kernighan); or __builtin_popcount, bits.OnesCount, int.bit_count()
x ^ y, then popcountHamming distance
popcount(x) & 1parity
bswap32(x) / bits.ReverseBytes32swap byte order (endianness)
bits.Reverse32(x)reverse bit order

Beware

  • Shifting by ≥ width is undefined in C/C++; masked in JS and Java (1 << 32 == 1).
  • JS bitwise ops truncate to 32 bits; use BigInt above that.
  • ~ on unsigned types in C widens; cast back.
  • Right shift of a negative signed value is implementation-defined in C before C++20 (arithmetic everywhere in practice).
  • Precedence: & binds looser than ==; write (x & m) == m.

Questions

Where can I try these?

The bitwise calculator shows every bit of the result for AND, OR, XOR, shifts and rotates at 8–64 bits, and the bitmask calculator builds masks from positions.