Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 923
J_mie6 Avatar asked Aug 04 '12 16:08

J_mie6


People also ask

How does bitwise operation work?

The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise AND operator must have integral types.

What is >> and << in Python?

They are bit shift operator which exists in many mainstream programming languages, << is the left shift and >> is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.

How bitwise NOT operator works in Python?

Python's bitwise NOT operator ~x inverts each bit from the binary representation of integer x so that 0 becomes 1 and 1 becomes 0. This is semantically the same as calculating ~x == -x-1 . For example, the bitwise NOT expression ~0 becomes -1 , ~9 becomes -10 , and ~32 becomes -33 .

What does >> mean in Python?

In Python >> is called right shift operator. It is a bitwise operator. It requires a bitwise representation of object as first operand. Bits are shifted to right by number of bits stipulated by second operand. Leading bits as towards left as a result of shifting are set to 0.


1 Answers

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!

like image 178
Mr Lister Avatar answered Sep 22 '22 00:09

Mr Lister