Bitwise Operators and Assertion
Learn about the usage of bitwise operators and assertions in Python.
We'll cover the following...
Bitwise operators
Bitwise operators allow us to work with the individual bits of a byte. There are many bitwise operators available, as shown in the table below.
Operator | Name | Purpose |
| NOT (also called complement operator) | It converts 0 to 1 and 1 to 0. |
| LEFT SHIFT | Shift out the desired number of bits from left. |
| RIGHT SHIFT | Shift out the desired number of bits from right. |
| AND | Check whether a bit is on / off. Put off a particular bit. |
| OR | Put on a particular bit. |
| XOR | It toggles a bit. |
The following code shows the usage of bitwise operators:
Press + to interact
ch = 32print(ch)dh = ~ch # toggles 0s to1s and 1s to 0sprint(dh)eh = ch << 3 # << shifts bits in ch 3 positions to leftprint(eh) # 32 x 2^3fh = ch >> 2 # >> shifts bits in ch 2 positions to rightprint(fh) # 32 / 2^2a = 45 & 32 # and bits of 45 and 32print(a)b = 45 | 32 # or bits of 45 and 32print(b)c = 45 ^ 32 # xor bits of 45 and 32print(c)
Remember:
- If we perform the
&
operation on anything with 0, it will become 0. - If we perform the
|
operation on anything with 1, it will become 1. - If we perform the
^
operation on 1 with 1, it