Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Bitwise Operators

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading