Reputation: 1
I find '&' in python means 'and' operation based on bit expression. Recently, I find a very smart code and one line is like 'i & -i' where i is a integer. How to understand the result of 'i & -i'. In addition, how python deal with negative integer '-i' for bit manipulation?
Upvotes: 0
Views: 388
Reputation: 3891
"i & -i" - this is clear all bits "1", but last significant one. For example:
i = 10(dec) = 00001010(bin)
i & -i will be 00000010(bin) = 2(dec)
By math terms, "i & -i" returns maximal 2^N, which is divider of "i".
More examples:
i(dec) i(bin) i&-i
1 1 1
5 101 1
8 1000 1000
12 1100 0100
Upvotes: 1