Bit Operations
Competitive Programming/Bit Manipulation.md
fIn programming, an n-bit integer is internally stored as a binary number that consists
of n bits. For example, the C++ type int is a 32-bit type, which means that every
int number consists of 32 bits. For example, the bit representation of the int
number 43 is
To convert a bit representation into a number, the formula is given by
Connections
- A signed number equals an unsigned number .
Bit Operations
- The and operation
x & yproduces a number that has one bits in positions where both x and y have one bits.- If a number is even, then
x & 1 = 0. - If a number is odd, then
x & 1 = 1. - A number is divisible by exactly when
x & (2^k-1) = 0.
- If a number is even, then
- The or operation
x | yproduces a number that has one bits in positions where at least one of and have one bits. - The xor operation
x^yproduces a number that has one bits in positions where exactly one of x and y have one bits - The not operation
~xproduces a number where all the bits of have been inverted. - The left bit shift
x << kappends zero bits to the number and the right bit shiftx >> kremoves the last bits from the number.- Note that and
- because and .
- A bit mask of the form
1 << khas one bit in position , and all other bits are zero. As a remark, the kth bit of a number is one exactly whenx & (1 << k)is not zero.x | (1 << k)sets the th bit of to onex & ~(1 << k)sets the th bit of to zero.x ^ (1 << k)inverts the th bit of .x & (x - 1)sets the last one bit of to zero.x | (x-1)inverts all the bits after the last one bit.- A positive number is a power of two exactly when
x & (x - 1) = 0.
Additional Functions
__builtin_clz(x): the number of zeros at the beginning of the bit representation__builtin_ctz(x): the number of zeros at the end of the bit representation__builtin_popcount(x): the number of ones in the bit representation__builtin_parity(x): the parity (even or odd) of the number of ones in the bit representation
Set Operations as Bit Operations
| Operation | Set Syntax | Bit Syntax |
|---|---|---|
| Intersection | ||
| Union | ||
| Complement | ||
| Difference | ||
| For example, the following code first constructs the sets and and then constructs the set : |
_int x = (1<<1)|(1<<3)|(1<<4)|(1<<8);_
_int y = (1<<3)|(1<<6)|(1<<8)|(1<<9);_
_int z = x|y;_
_cout << __builtin_popcount(z) << "\n"; // 6_