pythonbit-manipulation

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 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?


Solution

  • 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