Bitwise Operators
In Python, bitwise operators are used to perform operations on individual bits of binary representations of numbers. These operators work at the bit level and manipulate the binary digits of integers. Python provides the following bitwise operators:
Bitwise AND (
&
): It performs a bitwise AND operation between the corresponding bits of two integers. Each bit of the result is set to 1 only if both bits are 1. Example:5 & 3
returns1
(binary0101 & 0011 = 0001
).Bitwise OR (
|
): It performs a bitwise OR operation between the corresponding bits of two integers. Each bit of the result is set to 1 if at least one of the bits is 1. Example:5 | 3
returns7
(binary0101 | 0011 = 0111
).Bitwise XOR (
^
): It performs a bitwise XOR (exclusive OR) operation between the corresponding bits of two integers. Each bit of the result is set to 1 if the two bits are different. Example:5 ^ 3
returns6
(binary0101 ^ 0011 = 0110
).Bitwise NOT (
~
): It performs a bitwise negation operation on an integer. It flips all the bits, converting 0s to 1s and 1s to 0s. The result is the two’s complement of the number. Example:~5
returns-6
(binary~0101 = 1010
, which is the two’s complement representation of-6
).Left Shift (
<<
): It shifts the bits of the left operand to the left by the number of positions specified by the right operand. Zeros are shifted in from the right. Example:5 << 2
returns20
(binary0101 << 2 = 010100
, which is equivalent to decimal20
).Right Shift (
>>
): It shifts the bits of the left operand to the right by the number of positions specified by the right operand. In a right shift, the leftmost bit is filled with the sign bit (0 for non-negative numbers, 1 for negative numbers). Example:11 >> 1
returns5
(binary1011 >> 1 = 0101
, which is equivalent to decimal5
).
These bitwise operators are commonly used in low-level programming, optimization, and working with binary data. They allow you to manipulate individual bits and perform operations at a very fine-grained level.