Cover Image for Python Bitwise XOR Operator
188 views

Python Bitwise XOR Operator

The Python bitwise XOR (exclusive OR) operator is represented by the caret symbol ^. The bitwise XOR operator performs an XOR operation on the individual bits of two integers. It returns a new integer where each bit is set to 1 if the corresponding bits in the operands are different, and 0 if they are the same.

Here’s the syntax of the bitwise XOR operator:

Python
operand1 ^ operand2

Here are some examples of how the bitwise XOR operator works:

Python
# Example 1
a = 5  # Binary: 0101
b = 3  # Binary: 0011

result = a ^ b  # Binary: 0110, Decimal: 6
print(result)   # Output: 6

# Example 2
x = 0b1100  # Binary: 1100 (12 in decimal)
y = 0b1010  # Binary: 1010 (10 in decimal)

result = x ^ y  # Binary: 0110, Decimal: 6
print(result)    # Output: 6

In Example 1, we perform a bitwise XOR operation on integers a and b. The binary representation of a is 0101, and the binary representation of b is 0011. The result of the XOR operation is 0110, which is 6 in decimal.

In Example 2, we use binary literals to define the values of x and y. We then perform the XOR operation, resulting in the binary 0110, which is 6 in decimal.

The bitwise XOR operator can be useful in various programming scenarios, such as when you need to toggle specific bits or perform bitwise encryption and decryption operations.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS