Python Bitwise Operators
Bitwise Operators in Python
Bitwise operators are used to perform operations on individual bits of integer values. They manipulate the bits directly and are often used in low-level programming, cryptography, and performance-critical applications. Python supports several bitwise operators, which operate on integers as their operands.
List of Bitwise Operators
Operator | Description | Example | Result |
---|---|---|---|
& | Bitwise AND | a & b | Performs AND on each bit |
` | ` | Bitwise OR | `a |
^ | Bitwise XOR (exclusive OR) | a ^ b | Performs XOR on each bit |
~ | Bitwise NOT (one's complement) | ~a | Inverts all bits |
<< | Left shift | a << n | Shifts bits to the left by n positions |
>> | Right shift | a >> n | Shifts bits to the right by n positions |
Examples of Bitwise Operators
1. Bitwise AND (&
)
The &
operator compares each bit of two integers. If both bits are 1
, the resulting bit is 1
; otherwise, it's 0
.
2. Bitwise OR (|
)
The |
operator compares each bit of two integers. If at least one of the bits is 1
, the resulting bit is 1
.
3. Bitwise XOR (^
)
The ^
operator compares each bit of two integers. If the bits are different, the resulting bit is 1
; if they are the same, it's 0
.
4. Bitwise NOT (~
)
The ~
operator inverts the bits of its operand. It changes 1
to 0
and 0
to 1
.
5. Left Shift (<<
)
The <<
operator shifts the bits of the left operand to the left by the number of positions specified by the right operand. This effectively multiplies the number by 2
for each shift.
6. Right Shift (>>
)
The >>
operator shifts the bits of the left operand to the right by the number of positions specified by the right operand. This effectively divides the number by 2
for each shift.
Summary of Bitwise Operators:
&
: Bitwise AND. Returns a bit set to1
only if both corresponding bits are1
.|
: Bitwise OR. Returns a bit set to1
if at least one corresponding bit is1
.^
: Bitwise XOR. Returns a bit set to1
if corresponding bits are different.~
: Bitwise NOT. Inverts all bits.<<
: Left shift. Shifts bits to the left, effectively multiplying by2
.>>
: Right shift. Shifts bits to the right, effectively dividing by2
.
Bitwise operators are useful for tasks that involve binary manipulation, such as low-level programming, network protocols, and image processing.