[Python] How do bitwise operations work in Python?

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

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

    Continue reading...

Compartilhe esta Página