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:

Python3
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:

Python3
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:

Python3
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:

Python3
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:

Python3
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.

Bitwise Algorithm in Python

Similar Reads

What is Bitwise Algorithm?

A bitwise algorithm is a type of algorithm that operates on individual bits of data rather than on larger data types like integers or floating-point numbers. These algorithms manipulate bits directly, typically using bitwise operators such as AND, OR, XOR, left shift, right shift, and complement....

Common Bitwise Operator:

1. Bitwise AND (&) Operator:...

Bit Manipulation Techniques:

1. Checking if a Bit is Set:...