Python Forum
not bitwise ~15 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: not bitwise ~15 (/thread-22105.html)



not bitwise ~15 - 1885 - Oct-29-2019

>>~15
returns a -16
>>~15&255
returns 240

I'm not sure why.
Please throw me a bone.


RE: not bitwise ~15 - ichabod801 - Oct-30-2019

The integers are converted to twos-complement binary notation, where negative numbers start with a 1 and positive numbers start with a 0. However that depends on how many bits are used, because if you are using 8 bits or 16 bits, the first bit is a different bit. But that's machine dependent, so Python assumes there's an infinite number of 1's preceding the rest of the binary representation. So 15 is ...11111101111. When those bits are flipped by the not operator, the preceding ones are not flipped, giving you ...1111110000, which is how you would represent -16.

The 255 is represented as ...11111011111111. If we put that together with our -16 from above:

Output:
...11111011111111 ...11111111110000 ...11111011110000
Which is 128 + 64 + 32 + 16 = 240.


RE: not bitwise ~15 - newbieAuggie2019 - Oct-30-2019

(Oct-29-2019, 10:44 PM)1885 Wrote: >>~15
returns a -16
>>~15&255
returns 240

Hi!

The sign '~' returns the 'binary one's complement' of a number. So ~15 returns the binary complement of 15. The number '15' in binary in an 8 bit representation is '00001111' (128x0 + 64x0 + 32x0 + 16x0 + 8x1 + 4x1 + 2x1 + 1x1 = 15). In binary there can be only 0's and 1's, so the complement of a number in binary is substituting the 1's by 0's and vice versa. Therefore, the complement of '00001111' is '11110000', that is the signed 2's complement of the decimal -16.

The sign '&' performs bit by bit AND operation on the two values. That is done multiplying bit by bit the two values (0x0=0, 0x1=0, 1x0=0, 0x0=0). We saw already that ~15 is '11110000', and 255 is '11111111' (128x1 + 64x1 + 32x1 + 16x1 + 8x1 + 4x1 + 2x1 + 1x1 = 255):
'11110000'
'11111111' x
______________
'11110000'

and '11110000' (128x1 + 64x1 + 32x1 + 16x1 + 8x0 + 4x0 + 2x0 + 1x0 = 240) corresponds to the decimal number '240' (but also to the decimal from signed 2's complement '-16').

Sources:

https://data-flair.training/blogs/python-operator/

https://en.wikipedia.org/wiki/Bitwise_operation

https://en.wikipedia.org/wiki/Two%27s_complement

https://www.rapidtables.com/convert/number/binary-to-decimal.html

I hope it helps.

All the best,


RE: not bitwise ~15 - 1885 - Oct-30-2019

Thank so much ichabod801 and newbieAuggie2019
I appreciate the excellent descriptions!