I encountered this application example, and I understand the meaning of the bitwise operator symbols and the resulting value. However, I was confused at this part, because I thought we use these operators with only 0 and 1. (not integers..unless there are some conversion which I am not familiar of). Would greatly appreciate how the below was arrived at:
x = 4
y = 1
a = x & y
b = x | y
c = ~x
d = x ^ 5
e = x >> 2
f = x << 2
print(a, b, c, d, e, f) # 0 5 -5 1 1 16
>Solution :
The bitwise operators perform on the binary representations of the numbers:
x is 4 in decimal, which in binary is 100
y is 1 in decimal, which in binary is 001.
The & operator performs a bitwise AND operation on each corresponding pair of bits, so a = x & y is equivalent to 100 & 001, which equals 000 in binary, so your output is 0.
Same for the rest of the operations:
b = 100 | 001, which equals 101 in binary, i.e. 5 in decimal
c = ~100 –> 011 in binary, which in two’s complement representation represents -5 in decimal. So, c is -5.
d = 100 ^ 101 –> 001 in binary, 1 in decimal
e = 100 >> 2 –> 001 in binary, 1 in decimal
f = 100 << 2 –> 10000 in binary, 16 in decimal