J_mie6
J_mie6

Reputation: 720

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?

Upvotes: 7

Views: 19909

Answers (3)

Chase
Chase

Reputation: 1

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

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

Upvotes: 0

Mr Lister
Mr Lister

Reputation: 46559

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!

Upvotes: 7

paxdiablo
paxdiablo

Reputation: 881423

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

Upvotes: 7

Related Questions