a & b
a | b
a ^ b
~a
a << 1
a >> 1
Check if a number is odd or even
bool isOdd(int x) {
return x & 1;
}
Get the i-th bit
bool getBit(int x, int i) {
return (x & (1 << i)) != 0;
}
Set the i-th bit
void setBit(int &x, int i) {
x |= (1 << i);
}
Clear the i-th bit
void clearBit(int &x, int i) {
x &= ~(1 << i);
}
Toggle the i-th bit
void toggleBit(int &x, int i) {
x ^= (1 << i);
}
Count the number of set bits (Hamming Weight)
int countSetBits(int x) {
int count = 0;
while (x) {
count += x & 1;
x >>= 1;
}
return count;
}
Check if a number is a power of 2
bool isPowerOfTwo(int x) {
return x && !(x & (x - 1));
}