Bitwise operations are a way to directly work with the binary digits (bits) of a number.
In C++, these operations use specific symbols to manipulate bits in various ways. Let’s explore these operations and some cool tricks you can do with them!
Basic Bitwise Operators
- AND (
&
): Compares each bit of two numbers and returns a new number whose bits are 1 if both bits are 1, and 0 otherwise.
Example:
int result = 5 & 3; // result will be 1 (0000 0101 & 0000 0011 = 0000 0001)
2. OR (|
): Compares each bit of two numbers and returns a new number whose bits are 1 if at least one of the bits is 1.
Example:
int result = 5 | 3; // result will be 7 (0000 0101 | 0000 0011 = 0000 0111)
3. XOR (^
): Compares each bit of two numbers and returns a new number whose bits are 1 if the bits are different.
Example:
int result = 5 ^ 3; // result will be 6 (0000 0101 ^ 0000 0011 = 0000 0110)
4. NOT (~
): Flips all the bits of a number (0s become 1s and 1s become 0s).
Example:
int result = ~5; // result will be -6 (1111 1010)