Question

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?

Was it helpful?

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.

OTHER TIPS

Those are bitwise operators.

x & y Does a "bitwise and".

~ x Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1.

~x is a unary operator equivalent to (-x)-1 for numbers.

x &= y

is equivalent to

x = x & y

where & stands for binary and.

~ is a binary invertion operator.

bob &= lucy is shorter version of bob = bob & lucy. Basically, bitwise AND and store results value.

More about that - Unary arithmetics and bitwise operations @Python docs

(~) : Binary Ones Complement Operator is unary and has the efect of 'flipping' bits

For Example:

a = 0011 1100
(~a ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary  number

(&) : Binary AND Operator copies a bit to the result if it exists in both operands.

a = 0011 1100
b = 0000 1101
(a & b) will give 12 which is 0000 1100
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top