Bitwise OperationsLow-levelPerformance
Stage 9: Bitwise Operations in C++
A guide to manipulating individual bits of data. The key to optimization and low-level programming.
February 11, 20263 min read
Share:
Bitwise Operations: Thinking in Binary
Bitwise operations allow you to manipulate data at the lowest possible level – the level of individual bits (0s and 1s). In exams, these tasks often test your proficiency in logical thinking and understanding how numbers are represented in memory.
1. Basic Bitwise Operators
C++ has six main bitwise operators:
&(AND): Result is 1 only where both bits are 1.|(OR): Result is 1 if at least one bit is 1.^(XOR): Result is 1 if the bits are different (one is 0, the other is 1).~(NOT): Negation – turns 0 into 1 and 1 into 0.<<(Left Shift): Shifts bits to the left, padding with zeros from the right (effectively multiplying by ).>>(Right Shift): Shifts bits to the right (effectively integer division by ).
2. Practical Applications (Exam Tasks)
Checking if a number is even
Instead of % 2, we can check the least significant bit. If it is 0, the number is even.
cpp
if ((number & 1) == 0) {
std::cout << "Even";
}Setting a specific bit (Masking)
To set the n-th bit to 1 (counting from 0), use the | operator.
cpp
int number = 0;
int n = 3; // we want to set the 4th bit
number = number | (1 << n);Checking the value of the n-th bit
cpp
bool isSet = (number >> n) & 1;3. Bitwise Shifts and Performance
Bitwise shifts are significantly faster than standard multiplication or division by powers of two.
x << 1is the same asx * 2.x >> 1is the same asx / 2.
Exam Pitfalls
- Confusing logical vs bitwise operators: Never use
&&instead of&.&&returns onlytrue/false, while&operates on each pair of bits separately. - Operator Precedence: Bitwise operators have lower precedence than comparison operators. Always use parentheses!
x & 1 == 0will be interpreted asx & (1 == 0), which is an error. Write:(x & 1) == 0. - Negative Numbers: Bitwise shifts on negative numbers can behave differently depending on the compiler (Implementation Defined Behavior). Try to use
unsigned intfor bitwise operations.
Example: Swapping values without a temporary variable (XOR Swap)
cpp
a = a ^ b;
b = a ^ b;
a = a ^ b;