Python: Bitwise Operators
Literal expression for number in binary form
0b101
mean binary number 101
print(0 == 0b0) print(1 == 0b1) print(2 == 0b10) print(3 == 0b11)
Print number in binary form
print("{:b}".format(0) == "0") print("{:b}".format(1) == "1") print("{:b}".format(2) == "10") print("{:b}".format(3) == "11")
- "{:b}" means print in binary.
- "{:2b}" means print in binary, and use 2 slots.
Bitwise Operators
Bitwise And &
print(0b11 & 0b10 == 0b10)
Bitwise Or |
print(0b11 | 0b10 == 0b11)
Xor ^
.
return 1
if digits differ.
print(0b00 ^ 0b10 == 0b10)
Binary invert ~
print(~0b1 == -0b10)
- binary right shift
>>
- binary left shift
<<