How do bitwise operations work in Python?

扶醉桌前 提交于 2020-01-11 19:39:12

问题


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 is -11 (per the python command line) which is

01010
to
11011

only two of the bits have been inverted. Can anybody explain why it isn't 10101?

EDIT: After looking on my calculator I understand it a little better, But my own code for determining binary and ints is still being confused. Entering in (in byte mode) 11110101 gives me -11 but the same entered 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 one of you explain that?


回答1:


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
10101 add one gives negative eleven



回答2:


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!




回答3:


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

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



来源:https://stackoverflow.com/questions/11810113/how-do-bitwise-operations-work-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!