Bit manipulation is an essential technique in programming that involves operating directly on bits—the fundamental units of information in computers. It enables high-performance solutions for many computational problems, particularly in competitive programming, cryptography, embedded systems, and optimization tasks. Understanding bitwise operations can significantly improve code efficiency and reduce execution time.
Table of Contents
Understanding Bitwise Operators
Bitwise operations work at the binary level and are faster than arithmetic operations. In most programming languages, the following bitwise operators are available:
AND (&):
- Sets a bit if both corresponding bits are 1.
- Example: 5 & 3 (0101 & 0011) = 0001 (1 in decimal)
OR (|):
- Sets a bit if at least one of the corresponding bits is 1.
- Example: 5 | 3 (0101 | 0011) = 0111 (7 in decimal)
XOR (^):
- Sets a bit if only one of the corresponding bits is 1.
- Example: 5 ^ 3 (0101 ^ 0011) = 0110 (6 in decimal)
NOT (~):
- Inverts all bits (also known as bitwise complement).
- Example: ~5 (0101) = 1010 (in two’s complement representation, this is -6)
Left Shift (<<):
- Shifts bits to the left, effectively multiplying by powers of 2.
- Example: 5 << 1 (0101 << 1) = 1010 (10 in decimal)
Right Shift (>>):
- Shifts bits to the right, effectively dividing by powers of 2.
- Example: 5 >> 1 (0101 >> 1) = 0010 (2 in decimal)
Two’s Complement Representation
Two’s complement is the most common method of representing signed integers in binary systems. It simplifies arithmetic operations and eliminates the need for separate negative sign representation.
2's complement(2^n) = 1's complement + 1
PythonCommon Bit Manipulation Tricks
Checking if a Number is Even or Odd
A number is odd if its last bit is 1, and even if its last bit is 0.
if num & 1:
print("Odd")
else:
print("Even")
PythonSwapping Two Numbers Without a Temporary Variable
a = 5
b = 3
a = a ^ b
b = a ^ b
a = a ^ b
print(a, b) # Output: 3, 5
PythonChecking if a Number is a Power of Two
def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
print(is_power_of_two(16)) # True
print(is_power_of_two(18)) # False
PythonCounting the Number of Set Bits (Hamming Weight)
def count_set_bits(n):
count = 0
while n:
count += n & 1
n >>= 1
return count
print(count_set_bits(15)) # Output: 4 (1111 has four 1s)
PythonFinding the Only Non-Repeating Element in an Array
Using XOR, we can find a unique element when every other element appears twice.
def find_unique(arr):
result = 0
for num in arr:
result ^= num
return result
print(find_unique([2, 3, 5, 3, 2])) # Output: 5
PythonFinding the Position of the Rightmost Set Bit
def rightmost_set_bit(n):
return n & -n
print(rightmost_set_bit(18)) # Output: 2 (Binary: 10010, rightmost set bit is at 2)
PythonMultiplication Using Bit Manipulation
Bitwise shifts can be used to perform fast multiplication by powers of 2. Instead of using the multiplication operator, shifting left (<<) effectively multiplies a number by 2^k.
The left shift operator (n << k) is equivalent to multiplying n by 2^k. This is because shifting a binary number left by k positions effectively multiplies it by 2^k
Examples:
17n = 16n + n = n * pow(2,4) + n = (n << 4) + n
7n = 8n - n = n * pow(2,3) - n = (n << 3) - n
54n = 64n -10n = n * pow(2,6) - 10n = (n << 6) - 10n
PythonWhy Use This?
- Bitwise shifts are faster than multiplication because they are simple bit manipulations at the CPU level.
- This is commonly used in low-level programming (e.g., embedded systems, performance-sensitive code).
Applications of Bit Manipulation
- Competitive Programming: Faster solutions for problems involving subsets, bitmasking, and optimization.
- Cryptography: Bitwise operations play a crucial role in encryption algorithms.
- Embedded Systems: Used for direct hardware manipulation in microcontrollers.
- Image Processing: Manipulation of pixel values at the bit level.
- Networking: Efficient routing, packet processing, and error detection.
Conclusion
Bit manipulation is a powerful technique that enables efficient computations in various fields. Mastering bitwise operations allows programmers to write optimized code and solve complex problems with minimal resource consumption. By practising and applying these tricks, developers can improve their problem-solving skills and enhance the performance of their applications.