I got a code like this:
def f(x):
return 1 if x & (x-1) == 0 else 0
print(f(20))
Can anyone explain what this function is doing?
i need to understand x & x-1
meaning.
I got a code like this:
def f(x):
return 1 if x & (x-1) == 0 else 0
print(f(20))
Can anyone explain what this function is doing?
i need to understand x & x-1
meaning.
First up, go and have a look at this answer to see how bitwise operators work. Once, you understand that, just be aware that the expression x & x-1
(with unsigned x
, at least) will give you zero if and only if x
is a power of two or zero (I consider zero to be a special case simply because zero and'ed with anything gives you zero).
The reason x & (x - 1)
gives you zero for a power of two is because a power of two takes the binary form on the first line below (a single 1
bit followed by zero or more 0
bits) and subtracting one from it gives you the second form (with the bits all inverted from that single 1
bit onward):
10000000 = 128 (128)
01111111 = 127 (64 + 32 + 16 + 8 + 4 + 2 + 1)
-------- AND
00000000
So, if you and
them, all bits become zero. Note that no non-power-of-two other than zero has this property, for example 42
:
00101010 = 42 (32 + 8 + 2)
00101001 = 41 (32 + 8 + 1)
-------- AND
00101000 = 40 (32 + 8)