How do bitwise operations work in Python?

I found out about Bitwise operations today, and I found out that Not (~) inverts all bits, for example:

01010 to 10101 

which means that ~ 10 should be -5, but instead, I saw it was -11 (on the python command line), which is equal to

 01010 to 11011 

only two of the bits were inverted. Can anyone explain why this is not 10101?

EDIT: after looking at my calculator, I understand this a little better, but my own code for determining binary and ints is still confused. Entering (in byte mode) 11110101 gives me -11, but the same as in my code gives -117:

 def binaryToInt(biNum, bUnsigned = False): iNum = 0 bSign = int(biNum[0]) if not (bUnsigned or biNum[-1] == "u") else 0 biNum = biNum[(1 if not (bUnsigned or biNum[-1] == "u") else 0):(len(biNum) if biNum[-1] != "u" else -1)] for i in xrange(len(biNum)): iNum += int(biNum[i]) * 2**(len(biNum) - 1 - i) return (iNum if not bSign else -iNum) def intToBinary(iNum, bUnsigned = False): bSign = "1" if iNum < 0 else "0" iLoopNum = int((iNum ** 2) ** 0.5) #make positive! biNum = "" while iLoopNum: biNum += str(iLoopNum%2) iLoopNum /= 2 return bSign + biNum[::-1] if not bUnsigned else biNum[::-1] + "u" 

can any of you explain this?

+7
source share
3 answers

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

In two additions -11 there are 10101 , which is the correct bit inversion.

To cancel two additional numbers, you invert all the bits and add one:

 01011 eleven 10100 invert 10101 add one gives negative eleven 
+6
source

Assuming 32 bits, 10

 00000000000000000000000000001010 

and if you invert all these bits, you will get

 11111111111111111111111111110101 

or -11. Because it is 2 supplement system !

+7
source

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

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

0
source

Source: https://habr.com/ru/post/922121/


All Articles