What are Bitwise Operators (And, OR, XOR) in Python | Explained

What are Bitwise Operators (And, OR, XOR) in Python | Explained 


Bitwise operators are a set of operators that perform bit-level operations on integers. These operators are primarily used to perform bit manipulation on binary data.


In Python, the bitwise operators are:


AND (&)

OR (|)

XOR (^)

NOT (~)

Left Shift (<<)

Right Shift (>>)



Let's go through each of these operators in detail:


AND (&): The AND operator compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.


OR (|): The OR operator compares each bit of the first operand to the corresponding bit of the second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.


XOR (^): The XOR operator compares each bit of the first operand to the corresponding bit of the second operand. If the bits are different, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.


NOT (~): The NOT operator is a unary operator that inverts all the bits of the operand. If the operand is 0, the result is 1. If the operand is 1, the result is 0.


Left Shift (<<): The left shift operator shifts the bits of the operand to the left by the specified number of positions. This has the effect of multiplying the operand by 2 to the power of the number of positions shifted.


Right Shift (>>): The right shift operator shifts the bits of the operand to the right by the specified number of positions. This has the effect of dividing the operand by 2 to the power of the number of positions shifted.


Here is an example of how to use the bitwise operators in Python:


Copy code

# Perform bitwise AND

x = 10  # Binary representation: 1010

y = 4   # Binary representation: 0100

result = x & y  # Binary representation: 0000, decimal value: 0

print(result)


# Perform bitwise OR

x = 10  # Binary representation: 1010

y = 4   # Binary representation: 0100

result = x | y  # Binary representation: 1110, decimal value: 14

print(result)


# Perform bitwise XOR

x = 10  # Binary representation: 1010

y = 4   # Binary representation: 0100

result = x ^ y  # Binary representation: 1110, decimal value: 14

print(result)


# Perform bitwise NOT

x = 10  # Binary representation: 1010

result = ~x  # Binary representation: 0101, decimal value: -11

print(result)


# Perform left shift

x = 10  # Binary representation: 1010

result = x << 2  # Binary representation: 101000, decimal value: 40

print(result)


# Perform right shift

x = 10  # Binary representation: 1010

result = x >> 2  # Binary representation: 0010, decimal value: 2

print(result)

I hope this helps! Let me know if you have any questions.

Comments