Search⌘ K

Bitwise Operators and Assertion

Explore how bitwise operators allow manipulation of individual bits in Python and understand using assertion statements to check program assumptions dynamically. This lesson helps you debug by catching errors early and making your code more robust.

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:

Python 3.8
ch = 32
print(ch)
dh = ~ch # toggles 0s to1s and 1s to 0s
print(dh)
eh = ch << 3 # << shifts bits in ch 3 positions to left
print(eh) # 32 x 2^3
fh = ch >> 2 # >> shifts bits in ch 2 positions to right
print(fh) # 32 / 2^2
a = 45 & 32 # and bits of 45 and 32
print(a)
b = 45 | 32 # or bits of 45 and 32
print(b)
c = 45 ^ 32 # xor bits of 45 and 32
print(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
...