Skip to content Skip to sidebar Skip to footer

How Do Bitwise Operations Work In Python?

I have been learning about Bitwise operations today and I learned that Not (~) inverses all bits, e.g.: 01010 to 10101 which means ~10 should be -5 but instead I have seen that it

Solution 1:

Assuming that values are 32 bits, 10 is

00000000000000000000000000001010

and if you invert all those bits, you get

11111111111111111111111111110101

or -11. Because it's a 2's complement system!

Solution 2:

11011 is not -11. You have a misunderstanding of the encoding scheme for negative numbers.

In two's complement, -11 is 10101 which is the correct bit inversion.

To negate a two's complement number, you invert all bits and add one:

01011 eleven
10100 invert
10101addone gives negative eleven

Solution 3:

10101 is -11, because in binary, -X = ~X + 1.

So ~X = -X - 1 = -(X + 1).

Post a Comment for "How Do Bitwise Operations Work In Python?"