Bit Manipulation Techniques
1. Checking if a Bit is Set:
To check if a specific bit is set in an integer:
Implementation of Checking if a Bit is Set:
def is_bit_set(num, pos):
return (num & (1 << pos)) != 0
num = 5 # 0101 in binary
print(is_bit_set(num, 0)) # Check if the least significant bit is set
# Output: True
print(is_bit_set(num, 1)) # Check if the second least significant bit is set
# Output: False
Output
True False
2. Setting a Bit:
To set a specific bit in an integer:
Implementation of setting a bit:
def set_bit(num, pos):
return num | (1 << pos)
num = 5 # 0101 in binary
result = set_bit(num, 1) # Set the second least significant bit
print(result) # Output: 7 (0111 in binary)
Output
7
3. Clearing a Bit:
Implementation of clearing a bit:
def clear_bit(num, pos):
return num & ~(1 << pos)
num = 7 # 0111 in binary
result = clear_bit(num, 1) # Clear the second least significant bit
print(result) # Output: 5 (0101 in binary)
Output
5
4. Toggling a Bit:
To toggle a specific bit in an integer:
Implementation of toggling a bit:
def toggle_bit(num, pos):
return num ^ (1 << pos)
num = 5 # 0101 in binary
result = toggle_bit(num, 1) # Toggle the second least significant bit
print(result) # Output: 7 (0111 in binary)
Output
7
5. Counting Set Bits:
To count the number of set bits (1s) in an integer:
Implementation of counting set bits:
def count_set_bits(num):
count = 0
while num:
count += num & 1
num >>= 1
return count
num = 7 # 0111 in binary
print(count_set_bits(num)) # Output: 3
Output
3
Related article:
Bitwise Algorithm in Python
Bitwise algorithms refer to the use of bitwise operators to manipulate individual bits of data. Python provides a set of bitwise operators such as AND (&), OR (|), XOR (^), NOT (~), shift left (<<), and shift right (>>). These operators are commonly used in tasks like encryption, compression, graphics, communications over ports and sockets, embedded systems programming, and more. They can lead to more efficient code when used appropriately.