Bitwise operations

Basic types / Numbers / Integer

a = 5  # 0101
b = 6  # 0110

# And
c1 = a & b
# c1 is 4 (0100)

# Or
c2 = a | b
# c2 is 7 (0111)

# Xor
c3 = a ^ b
# c3 is 3 (0011)

# shift right
c4 = a >> 1
# c4 is 2 (0010)

# shift left
c5 = b << 1
# c5 is 12 (1100)

# bits inversion
c6 = ~b
# c6 is -7 (-111)

# No fixed width: a mask keeps 8 bits
c7 = ~b & 0xFF
# c7 is 249 (11111001)

print(f"{c1 = }: {c1:04b}")
print(f"{c2 = }: {c2:04b}")
print(f"{c3 = }: {c3:04b}")
print(f"{c4 = }: {c4:04b}")
print(f"{c5 = }: {c5:04b}")
print(f"{c6 = }: {c6:04b}")
print(f"{c7 = }: {c7:04b}")