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.
Every idiom here works in C, Go, Rust, Java and JavaScript (32-bit) with the same operators; Python too, with unbounded integers.
| a & b | AND: 1 where both are 1 |
| a | b | OR: 1 where either is 1 |
| a ^ b | XOR: 1 where they differ |
| ~a | NOT: flip all bits (= −a − 1 in two's complement) |
| a << n | shift left: × 2ⁿ |
| a >> n | shift right: ÷ 2ⁿ, rounds toward −∞ for signed (arithmetic) |
| a >>> n | logical right shift (JS, Java); unsigned types elsewhere |
| x & (1 << n) | test: non-zero if set |
| (x >> n) & 1 | get 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 |
| (1 << n) - 1 | mask of the low n bits |
| ((1 << w) - 1) << lo | mask 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) == FLAGS | all flags set |
| x & FLAGS | any flag set |
| x & -x | isolate 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⌋ |
| x && !(x & (x - 1)) | is a power of two |
| (x & 1) == 0 | is even |
| (x ^ y) < 0 | opposite signs (signed) |
| (x & (a - 1)) == 0 | aligned to a (a = 2ⁿ) |
| x == (x & 0xFF) | fits in a byte |
| (x + a - 1) & -a | round up to multiple of a (a = 2ⁿ) |
| x & -a | round down to multiple of a |
| x & (a - 1) | x mod a (a = 2ⁿ, x ≥ 0) |
| (x + y) >> 1 | average (may overflow); (x & y) + ((x ^ y) >> 1) does not |
| x ^= y; y ^= x; x ^= y | swap 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 |
| while (x) { x &= x - 1; n++; } | popcount (Kernighan); or __builtin_popcount, bits.OnesCount, int.bit_count() |
| x ^ y, then popcount | Hamming distance |
| popcount(x) & 1 | parity |
| bswap32(x) / bits.ReverseBytes32 | swap byte order (endianness) |
| bits.Reverse32(x) | reverse bit order |
1 << 32 == 1).~ on unsigned types in C widens; cast back.& binds looser than ==; write (x & m) == m.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.