Bitwise Algorithm in Python
Last Updated :
18 Apr, 2024
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
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:
The bitwise AND operator is denoted using a single ampersand symbol, i.e. &. The & operator takes two equal-length bit patterns as parameters. The two-bit integers are compared. If the bits in the compared positions of the bit patterns are 1, then the resulting bit is 1. If not, it is 0.
Implementation of AND operator:
Python3
a = 7
b = 4
result = a & b
print(result)
# This code is contributed by akashish__
2. Bitwise OR (|
) Operator:
The | Operator takes two equivalent length bit designs as boundaries; if the two bits in the looked-at position are 0, the next bit is zero. If not, it is 1.
Implementation of OR operator:
Python3
a = 12
b = 25
result = a | b
print(result)
# This code is contributed by garg28harsh.
3. Bitwise XOR (^
) Operator:
The ^ operator (also known as the XOR operator) stands for Exclusive Or. Here, if bits in the compared position do not match their resulting bit is 1. i.e, The result of the bitwise XOR operator is 1 if the corresponding bits of two operands are opposite, otherwise 0.
Implementation of XOR operator:
Python3
a = 12
b = 25
result = a ^ b
print(result)
# This code is contributed by garg28harsh.
4. Bitwise NOT (~
) Operator:
All the above three bitwise operators are binary operators (i.e, requiring two operands in order to operate). Unlike other bitwise operators, this one requires only one operand to operate.
The bitwise Not Operator takes a single value and returns its one’s complement. The one’s complement of a binary number is obtained by toggling all bits in it, i.e, transforming the 0 bit to 1 and the 1 bit to 0.
Implementation of NOT operator:
Python3
a = 0
print("Value of a without using NOT operator: " , a)
print("Inverting using NOT operator (with sign bit): " , (~a))
print("Inverting using NOT operator (without sign bit): " , int(not(a)))
# This code is contributed by akashish__
OutputValue of a without using NOT operator: 0
Inverting using NOT operator (with sign bit): -1
Inverting using NOT operator (without sign bit): 1
5. Left-Shift (<<) Operator:
The left shift operator is denoted by the double left arrow key (<<). The general syntax for left shift is shift-expression << k. The left-shift operator causes the bits in shift expression to be shifted to the left by the number of positions specified by k. The bit positions that the shift operation has vacated are zero-filled.
Implementation of Left shift operator:
Python3
# Python code for the above approach
num1 = 1024
bt1 = bin(num1)[2:].zfill(32)
print(bt1)
num2 = num1 << 1
bt2 = bin(num2)[2:].zfill(32)
print(bt2)
num3 = num1 << 2
bitset13 = bin(num3)[2:].zfill(16)
print(bitset13)
# This code is contributed by Prince Kumar
Output00000000000000000000010000000000
00000000000000000000100000000000
0001000000000000
6. Right-Shift (>>) Operator:
The right shift operator is denoted by the double right arrow key (>>). The general syntax for the right shift is “shift-expression >> k”. The right-shift operator causes the bits in shift expression to be shifted to the right by the number of positions specified by k. For unsigned numbers, the bit positions that the shift operation has vacated are zero-filled. For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used.
Implementation of Right shift operator:
Python3
def main():
num1 = 1024
bt1 = bin(num1)[2:].zfill(32)
print(bt1)
num2 = num1 >> 1
bt2 = bin(num2)[2:].zfill(32)
print(bt2)
num3 = num1 >> 2
bitset13 = bin(num3)[2:].zfill(16)
print(bitset13)
if __name__ == "__main__":
main()
Output00000000000000000000010000000000
00000000000000000000001000000000
0000000100000000
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
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)
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)
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)
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
Related article:
Similar Reads
Bitwise Algorithms
Bitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift. BasicsIntroduction to Bitwise Algori
4 min read
Searching Algorithms in Python
Searching algorithms are fundamental techniques used to find an element or a value within a collection of data. In this tutorial, we'll explore some of the most commonly used searching algorithms in Python. These algorithms include Linear Search, Binary Search, Interpolation Search, and Jump Search.
6 min read
XOR Basis Algorithm
The XOR operation between two numbers P and Q can be looked in a different way as the bitwise sum modulo 2 on the bits of P and Q. Consider P = 10010 and Q = 00110. Starting from leftmost, we verify the above statement : (1 + 0) % 2 = 1 (0 + 0) % 2 = 0 (0 + 1) % 2 = 1 (1 + 1) % 2 = 0 (0 + 0) % 2 = 0
9 min read
Bitwise Algorithms - Basic Practice Problems
Bitwise algorithms are a category of algorithms that operate on individual bits within a data unit, rather than the entire data unit itself. They leverage bitwise operators, which are special operators designed to perform operations on bits. Common bitwise operators include AND (&), OR (|), XOR
5 min read
Bitwise Algorithms - Intermediate Practice Problems
Bitwise operations are fundamental to computer programming and problem-solving. At the intermediate level, you'll explore more complex bitwise algorithms and techniques to solve a variety of coding challenges. This includes topics like bit manipulation, number theory, and optimization using bitwise
7 min read
Divide and Conquer in Python
Divide and Conquer is an effective approach for managing challenges that divides a major problem into smaller, easier-to-manage subproblems. The solution to the main problem is obtained by combining the final solutions from multiple individually solved subproblems. This approach works especially wel
3 min read
Convert Bytes To Bits in Python
Converting bytes to bits in Python involves representing each byte in its binary form, where each byte is composed of 8 bits. For example , a byte like 0xAB (which is 171 in decimal) would be represented as '10101011' in binary. Letâs explore a few techniques to convert bytes to bits in Python. Usin
2 min read
Binary Heap in Python
A Binary Heap is a complete Binary Tree that is used to store data efficiently to get the max or min element based on its structure. A Binary Heap is either a Min Heap or a Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in a Binary Heap. The same property
3 min read
Arithmetic operations with std::bitset in C++
A bitset is an array of boolean values, but each boolean value is not stored separately. Instead, bitset optimizes the space such that each bool takes 1-bit space only, so space taken by bitset say, bs is less than that of bool bs[N] and vector<bool> bs(N). However, a limitation of bitset is,
3 min read
Bitwise Operators in C++
In C+, Bitwise Operators are the operators that are used to perform bit-level operations on the integers. While performing these operations, integers are considered as sequences of binary digits. These operators are useful for low-level programming, system programming, and optimizing performance. C+
6 min read