Skip to main content

Bit Ops Cheat Sheet

OperationSymbolMeaningExample
ANDa & bBit = 1 if both bits = 16 & 3 = 2
ORa | bBit = 1 if at least one bit = 16 | 3 = 7
XORa ^ bBit = 1 if bits differ6 ^ 3 = 5
NOT~aBitwise inversion (two’s complement)~5 = -6
OperationSymbolDescription
Left shifta << kMultiplies by 2^k
Arithmetic right shifta >> kDivides by 2^k, sign-extended
Logical right shifta >>> kShifts right with zero fill

Bit Manipulation

Check the i-th bit

((x >> i) & 1) == 1

Set the i-th bit

x |= (1 << i);

Clear the i-th bit

x &= ~(1 << i);

Toggle the i-th bit

x ^= (1 << i);

Common Bit Tricks

Check if x is even

(x & 1) == 0

Get the lowest set bit (LSB)

int lsb = x & -x;

Remove the lowest set bit

x &= (x - 1);

Check if x is a power of two

(x > 0) && ((x & (x - 1)) == 0)

XOR swap (not recommended in practice)

a ^= b;
b ^= a;
a ^= b;

Masks

0xFF — lowest 8 bits 0xFFFF — lowest 16 bits 0xFFFFFFFF — all 32 bits (int)

Extract an 8-bit value:

int b = x & 0xFF;

Java-Specific Notes

  • Bitwise operations on byte and short promote to int. Cast back if needed:
byte b = (byte)(b << 1);
  • >>> Works only on int and long as an unsigned shift.

Extract the Lowest Set Bit (LSB)

int lsb = x & -x;

Unique Value In Array (XOR)

int x = 0;
for (int v : arr) {
x ^= v;
}
return x;