Bitwise operators in python – If you’re new to Python programming, you might be wondering what bitwise operators are and how they work. Simply put, bitwise operators are used to perform operations on binary numbers.
These operators are represented by symbols like &, |, ^, and ~, and they work on individual bits of binary numbers.
In this article, we will explore bitwise operators in Python and how they can be used in programming. We will cover the following topics:
- What are Bitwise Operators?
- Types of Bitwise Operators
- AND Operator
- OR Operator
- XOR Operator
- NOT Operator
- Left Shift Operator
- Right Shift Operator
- Bitwise Operators in Python
- Practical Applications of Bitwise Operators
Let’s get started!
1. What are Bitwise Operators?
Bitwise operators are used to perform operations on binary numbers. In computing, everything is represented in binary form, which consists of only two digits – 0 and 1.
A binary digit is also called a bit. Bitwise operators are used to manipulate these bits to perform various operations.
2. Types of Bitwise Operators
There are six types of bitwise operators in Python:
- AND (&)
- OR (|)
- XOR (^)
- NOT (~)
- Left Shift (<<)
- Right Shift (>>)
3. AND Operator
The AND operator in Python is used to perform a bitwise AND operation on two numbers. The AND operator is represented by the symbol ‘&’. It returns 1 if both the bits are 1, otherwise it returns 0.
Let’s take a look at the truth table for the AND operator:
a | b | a & b |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
As you can see, the AND operator returns 1 only when both the bits are 1.
Now, let’s take a look at an example of using the AND operator in Python:
a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = a & b # 12 = 0000 1100 print("Result of bitwise AND: ", c) Output: Result of bitwise AND: 12
In this example, we are performing a bitwise AND operation on the values of a
and b
.
The binary representation of a
is 0011 1100
, and the binary representation of b
is 0000 1101
.
When we perform a bitwise AND operation on these two values, we get the value 0000 1100
, which is equal to 12 in decimal.
Therefore, the output of the above code will be:
Result of bitwise AND: 12
4. OR Operator
The OR operator is a bitwise operator that takes two operands and performs a logical OR operation on each pair of corresponding bits. The symbol ‘|’ is used to represent the OR operator in Python.
It returns 1 if either of the bits is 1, otherwise it returns 0. Here’s the truth table for the OR operator. When we apply the OR operator to two bits, it returns 1 if either of the bits is 1, and 0 if both bits are 0. The truth table for the OR operator is as follows:
a | b | a OR b |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
Here’s an example of using the OR operator in Python:
a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = a | b # 61 = 0011 1101 print("Result of bitwise OR: ", c) Output: Result of bitwise OR: 61
As you can see from the truth table, the OR operator returns 1 only when at least one of the input bits is 1.
In the example provided, we have two variables ‘a’ and ‘b’ with the values 60 and 13 respectively. In binary, 60 is represented as 0011 1100 and 13 is represented as 0000 1101.
When we perform the bitwise OR operation between ‘a’ and ‘b’ using the ‘|’ operator, we get 0011 1101, which is equal to 61 in decimal.
So the final output of the program is:
Result of bitwise OR: 61
5. XOR Operator
The XOR operator, also known as the “exclusive or” operator, is used to perform a bitwise comparison of two values. It returns a value of 1 for each bit position where the corresponding bits of the operands are different, and 0 where they are the same. The XOR operator is represented by the symbol ‘^’.
Here’s the truth table for the XOR operator:
a | b | a ^ b |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Here’s an example of using the XOR operator in Python:
a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = a ^ b # 49 = 0011 0001 print("Result of bitwise XOR: ", c) Output: Result of bitwise XOR: 49
In this example, the variable ‘a’ is assigned the value 60, which is equivalent to the binary number 0011 1100. The variable ‘b’ is assigned the value 13, which is equivalent to the binary number 0000 1101.
When we perform the XOR operation between ‘a’ and ‘b’, we get the result of 49, which is equivalent to the binary number 0011 0001. This is because the XOR operator returns 1 for each bit position where the corresponding bits of the operands are different, and 0 where they are the same.
Overall, the XOR operator is commonly used in computer programming for tasks such as encryption, error detection, and data validation.
6. NOT Operator
The NOT operator is represented by the symbol ‘~’. It inverts the value of a single bit. If the bit is 0, it returns 1 and if the bit is 1, it returns 0.
Here’s the truth table for the NOT operator:
a | ~a |
---|---|
0 | 1 |
1 | 0 |
As you can see from the table, the NOT operator simply flips the value of the bit. For example, if the input is 0, the NOT operator returns 1. Similarly, if the input is 1, the NOT operator returns 0.
Here’s an example of how to use the NOT operator in Python:
a = 60 # 60 = 0011 1100 b = ~a # -61 = 1100 0011 print("Result of bitwise NOT: ", b) Output: Result of bitwise NOT: -61
In this example, we use the NOT operator to invert the value of the variable ‘a’, which is 60 in binary (0011 1100). The NOT operator inverts each bit in the binary representation of ‘a’, resulting in -61 in binary (1100 0011).
7. Left Shift Operator
The Left Shift Operator in Python is represented by the ‘<<‘ symbol. It is used to shift the bits of a number to the left by a specified number of positions. The left shift operation is equivalent to multiplying the number by 2 to the power of the number of positions shifted.
The general syntax for the left shift operator is as follows:
number << n
Here, ‘number’ is the number that you want to shift and ‘n’ is the number of positions you want to shift it by.
To understand the left shift operator, let’s take an example. Suppose we have a number 10 in binary form, which is 1010. Now, if we shift this number to the left by 2 positions, we get:
1010 << 2 = 101000
As you can see, the number has been shifted to the left by 2 positions and two 0’s have been added to the right end of the binary representation.
Here’s a truth table for the left shift operator:
Left Operand (x) | Right Operand (y) | x << y |
---|---|---|
0 | n | 0 |
n | 0 | n |
n | m | n * 2^m |
Let’s take an example to understand how to use the left shift operator in Python:
a = 5 # 5 in binary is 101 b = 2 c = a << b # 10100 in binary, which is 20 in decimal print(c) Output: Result of bitwise left shift : 20
In the above example, we have a variable ‘a’ which is equal to 5 in decimal form, which is 101 in binary form. We also have a variable ‘b’ which is equal to 2.
Now, we shift the bits of ‘a’ to the left by 2 positions using the left shift operator and store the result in the variable ‘c’.
The result of the left shift operation is 10100 in binary form, which is equal to 20 in decimal form. Finally, we print the value of ‘c’, which is 20.
The left shift operator is commonly used in Python when working with binary numbers and bitwise operations.
8. Right Shift Operator
The right shift operator (>>) shifts the bits of a number to the right by a specified number of positions. The syntax for the right shift operator is as follows:
a >> n
where a
is the number to be shifted and n
is the number of positions to shift the bits. The right shift operator works by moving all the bits in a
to the right by n
positions. The leftmost n
bits are discarded, and the rightmost n
bits are filled with zeroes.
Here’s an example of using the right shift operator in Python:
a = 60 # 60 = 0011 1100 b = a >> 2 # 15 = 0000 1111 print("Result of bitwise right shift: ", b) Output: Result of bitwise right shift: 15
In this example, the variable a
is assigned the value 60, which is represented in binary as 0011 1100
. The right shift operator >>
is used to shift the bits of a
to the right by 2 positions, resulting in the binary value 0000 1111
, which is equivalent to the decimal value 15.
Here’s a truth table for the right shift operator:
a | n | a >> n |
---|---|---|
0 | n | 0 |
1 | n | 0 or 1 |
0 | 0 | 0 |
1 | 0 | 1 |
In the table, a
is the original bit value, n
is the number of positions to shift the bits to the right, and a >> n
is the result of the right shift operation. As you can see, the right shift operator always fills the vacated leftmost bits with zeroes.
9. Bitwise Operators in Python
Bitwise operators are used to manipulate the individual bits of binary numbers. Python supports six bitwise operators:
- Bitwise AND (&)
- Bitwise OR (|)
- Bitwise XOR (^)
- Bitwise NOT (~)
- Left shift (<<)
- Right shift (>>)
Let’s take a closer look at each one.
1. Bitwise AND (&)
The bitwise AND operator returns a 1 in each bit position where both corresponding bits are 1.
Here’s an example:
a = 0b1100 b = 0b1010 c = a & b # 0b1000
In this example, a
is binary for 12, and b
is binary for 10. The result of a & b
is binary for 8, which is the binary value where both a
and b
have a 1 in the same bit position.
2. Bitwise OR (|)
The bitwise OR operator returns a 1 in each bit position where at least one corresponding bit is 1.
Here’s an example:
a = 0b1100 b = 0b1010 c = a | b # 0b1110
In this example, a
is binary for 12, and b
is binary for 10. The result of a | b
is binary for 14, which is the binary value where either a
or b
have a 1 in the same bit position.
3. Bitwise XOR (^)
The bitwise XOR operator returns a 1 in each bit position where the corresponding bits are different.
Here’s an example:
a = 0b1100 b = 0b1010 c = a ^ b # 0b0110
In this example, a
is binary for 12, and b
is binary for 10. The result of a ^ b
is binary for 6, which is the binary value where a
and b
have a different bit in the same bit position.
4. Bitwise NOT (~)
The bitwise NOT operator returns the complement of a binary number, which is the inverse of each bit (1s become 0s and vice versa).
Here’s an example:
a = 0b1100 b = ~a # -13
In this example, a
is binary for 12. The result of ~a
is binary for -13, which is the two’s complement of the binary number.
5. Left shift (<<)
The left shift operator shifts the bits of a binary number to the left by a specified number of positions. This is equivalent to multiplying the binary number by 2 raised to the power of the shift amount.
Here’s an example:
a = 0b1100 b = a << 2 # 0b110000
In this example, a
is binary for 12. The result of a << 2
is binary for 48, which is a
shifted to the left by 2 bits.
6. Right shift (>>)
The right shift operator shifts the bits of a binary number to the right by a specified number of positions. This is equivalent to dividing the binary number by 2 raised to the power of the shift amount.
Here’s an example:
a = 0b1100 b = a >> 2 # 0b0011
In this example, we start with the binary representation of the number 12, which is 0b1100
. We then use the right shift operator >>
to shift the bits in a
two places to the right, resulting in 0b0011
.
The two rightmost bits are dropped, and the two leftmost bits are set to 0. This is because we’re effectively dividing the value of a
by 2^2, or 4. So, b
has the decimal value 3.
It’s important to note that the right shift operator can also be used with a signed integer. In this case, the most significant bit (the leftmost bit) is used to determine the sign of the number.
For example:
a = -12 # -12 in two's complement is 0b11111100 b = a >> 2 # -3 in two's complement is 0b11111101
In this example, we start with the two’s complement representation of -12, which is 0b11111100
. We then shift the bits two places to the right using the >>
operator. The result is 0b11111101
, which represents -3 in two’s complement notation.
This happens because the most significant bit is a 1, indicating a negative number. When we shift the bits to the right, we preserve the value of the most significant bit, resulting in a negative number with a different value.
In general, bitwise operators can be a powerful tool for performing low-level operations on binary data. However, they should be used with care, as they can be easy to misuse and can lead to subtle bugs if not used correctly.
10. Practical Applications of Bitwise Operators
Here are some practical applications of bitwise operators in Python, along with examples and tables:
Setting and clearing flags: Bitwise operators can be used to set or clear specific bits in a number to represent different flags or options.
For example, let’s say we want to represent four different options using the four least significant bits of a number, with 1 indicating that the option is selected and 0 indicating that it is not.
We can use the OR operator to set a bit and the AND operator with the NOT operator to clear a bit:
# Setting and clearing flags option1 = 0b0001 # Select option 1 option2 = 0b0010 # Select option 2 option3 = 0b0100 # Select option 3 option4 = 0b1000 # Select option 4 options = 0b0000 # No options selected yet # Set options 1 and 3 options |= option1 | option3 print(bin(options)) # 0b0101 # Clear option 1 and set option 2 options &= ~option1 | option2 print(bin(options)) # 0b0010
Here, we use the OR operator |
to set the first and third bits of options
to 1, which represents selecting options 1 and 3. Then we use the AND operator &
with the NOT operator ~
to clear the first bit and set the second bit to 1, which represents clearing option 1 and selecting option 2.
Encoding and decoding data: Bitwise operators can also be used to encode and decode data by representing characters or data using their binary values.
For example, let’s say we want to encode the message “hello” as a series of binary values. We can use the ord()
function to get the ASCII code for each character, then use the bitwise OR operator to combine the codes into a single number:
# Encoding data message = "hello" encoded = 0 for c in message: encoded <<= 8 # Shift left by 8 bits for each new character encoded |= ord(c) print(bin(encoded)) # 0b110100001100101011011000110110001101111
Here, we shift the current value of encoded
left by 8 bits for each new character, then use the OR operator |
to combine the ASCII code for the current character with the previous value of encoded
.
To decode the data, we can use the bitwise AND and right shift operators to extract the original values:
# Decoding data decoded = "" while encoded: c = encoded & 0xFF # Extract the least significant 8 bits decoded = chr(c) + decoded encoded >>= 8 # Shift right by 8 bits to extract the next character print(decoded) # "hello"
Here, we extract the least significant 8 bits of encoded
using the AND operator &
and the mask 0xFF
, which gives us the ASCII code for the last character. We then use the chr()
function to convert the code back into a character and add it to the beginning of the decoded message. Finally, we shift the value of encoded
right by 8 bits to extract the next character, repeating the process until all characters have been decoded.
Bit manipulation: Bitwise operators can also be used for various other bit manipulation tasks, such as swapping the values of two variables without using a temporary variable:
# Swapping values without a temporary variable
Another practical application of bitwise operators is swapping the values of two variables without using a temporary variable. This technique can be useful in cases where memory space is limited or when the temporary variable may cause performance issues.
Here’s how it works. Let’s say we have two variables, a
and b
, and we want to swap their values:
a = 10 b = 5 print("Before swapping: a =", a, "b =", b) a = a ^ b b = a ^ b a = a ^ b print("After swapping: a =", a, "b =", b) Output: Before swapping: a = 10 b = 5 After swapping: a = 5 b = 10
Let’s break it down step by step:
a = a ^ b
: This sets the value ofa
to the result of performing the XOR operation ona
andb
. This effectively setsa
to the bitwise difference betweena
andb
.b = a ^ b
: This sets the value ofb
to the result of performing the XOR operation ona
andb
. Sincea
is now the bitwise difference betweena
andb
,b
will be set to the original value ofa
.a = a ^ b
: This sets the value ofa
to the result of performing the XOR operation ona
andb
. Sinceb
is now the original value ofa
,a
will be set to the original value ofb
.
After these three steps, the values of a
and b
will have been swapped:
print(a) # Output: 5
print(b) # Output: 10
This technique works because the XOR operation is both commutative and associative. This means that the order in which we perform the operations does not matter, and we can safely use the same variables for both the inputs and outputs of each operation.
Using bitwise operators to swap values can be faster than using a temporary variable, especially in cases where memory access is slow. However, it can also make your code harder to read and understand, so use it judiciously.
Conclusion
bitwise operators are an important feature of Python that allow us to manipulate individual bits of binary numbers. These operators can be used for a variety of tasks such as setting and clearing flags, performing logical operations, and bit manipulation.
Understanding bitwise operators is essential for anyone working with low-level programming, cryptography, or embedded systems. By using bitwise operators, we can write more efficient and optimized code, which is especially important when working with large datasets or complex algorithms.
With the help of examples and tables, this beginner’s guide to bitwise operators in Python should provide a solid foundation for anyone looking to learn this important concept.