Which of the following is a bitwise operator in Python?
a) and
b) or
c) ^
d) not
Answer:
c) ^
Explanation:
The ^
operator in Python is a bitwise XOR (exclusive OR) operator. It compares each bit of its operands and returns 1 for each bit position where the corresponding bits of the operands differ (i.e., one is 1, and the other is 0). If the corresponding bits are the same, it returns 0.
result = 5 ^ 3 # result is 6, because 5 (101 in binary) XOR 3 (011 in binary) is 110 in binary
Bitwise operators are powerful tools in Python, especially in low-level programming, cryptography, and situations where you need to manipulate individual bits of data.
Other common bitwise operators include &
(AND), |
(OR), ~
(NOT), and <<
(left shift) and >>
(right shift). Understanding how these operators work is essential for tasks involving binary data processing.