Bit Operations
You'll learn about the different bit operators present in Python in this lesson.
We'll cover the following
Bit operators overview
The following bit operators may be applied to integers.
Bit Operator | Description |
---|---|
~ |
Bitwise complement |
& |
Bitwise and |
| |
Bitwise or |
^ |
Bitwise exclusive or |
<< |
Left shift |
>> |
Right shift |
In case you are unfamiliar with these operators, each number is used in its binary notation, with 0
consisting of all zero bits, and -1
consisting of all one bits.
Bitwise complement (~
)
Bitwise complement changes every 1 to a 0 and every 0 to a 1. Numerically, the result is the same as changing the sign of the number and then subtracting 1.
For example, in the following example, when the ~
operator is applied on the integer 50, we get -51.This is because the bitwise complement first changes the sign of 50, making it negative, and then subtracts 1 from it, adding the two negative integers together to give -51.
Get hands-on with 1400+ tech skills courses.