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?
Asked
Active
Viewed 304 times
0
-
1Negative numbers are in [two's complement](https://en.wikipedia.org/wiki/Two's_complement) with an infinite number of leading ones (just like positive numbers have an infinite number of leading zeros). – Kevin Feb 12 '17 at 19:30
-
1Yes, bit manipulation is very important because that's how your CPU does maths! [Very interesting read](https://graphics.stanford.edu/~seander/bithacks.html), as well as [this](https://www.hackerearth.com/practice/notes/bit-manipulation/). – ForceBru Feb 12 '17 at 19:31
-
2Essentially a duplicate of http://stackoverflow.com/questions/41969429/why-the-bit-operation-i-i-equals-to-rightmost-bit, aside from the slight caveat that Python integers aren't fixed-width. – user2357112 Feb 12 '17 at 19:33
-
@user2357112 the proof I gave there also applies to left-infinite bit strings so it proves it for Python-type integers as well – harold Feb 12 '17 at 21:14
-
@user2357112 did you realize that you are genius? – Complex Feb 13 '17 at 22:46
1 Answers
1
"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

olegarch
- 3,670
- 1
- 20
- 19