Search code examples
pythonnotation

What are the meanings of the "~" and "&=" symbols in python?


I saw the following in a python group:

>> bookStyle = aui.AUI_NB_DEFAULT_STYLE
>> bookStyle &= ~(aui.AUI_NB_CLOSE_ON_ACTIVE_TAB)

Could you explain the second statement?? What does &= and ~ do?


Solution

  • As per the bitwise operators documentation,

    The unary ~ (invert) operator yields the bitwise inversion of its plain or long integer argument. The bitwise inversion of x is defined as -(x+1). It only applies to integral numbers.

    &= can be understood like this

    bookStyle = bookStyle & ~(aui.AUI_NB_CLOSE_ON_ACTIVE_TAB)
    

    So, we basically, invert the value of aui.AUI_NB_CLOSE_ON_ACTIVE_TAB and then check if all the ON bits in the inverted value are ON in bookStyle as well.

    The ~ can be understood better with 32 bit arithmetic like this

    5 can be represented in 32 bit Binary like this

    print format(5 & (1 << 32) - 1, "032b")
    # 00000000000000000000000000000101
    

    Now, when we do ~5 result will be

    print ~5
    # -6
    

    So, lets print -6 in Binary

    print format(-6 & (1 << 32) - 1, "032b")
    # 11111111111111111111111111111010
    

    If we compare the values,

    00000000000000000000000000000101
    11111111111111111111111111111010
    

    you get the idea what exactly is happening internally.