Can anyone help what n&-n
means??
And what is the significance of it.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
I would add a self-explanatory example to the Mark Randsom's wonderful exposition.
It's just a bitwise-and of the number. Negative numbers are represented as two's complement.
So for instance, bitwise and of 7&(-7) is x00000111 & x11111001 = x00000001 = 1
N&(-N)
will give you position of the first bit'1'
in binary form ofN
. For example:One application of this trick is to convert an integer to sum of power-of-2. For example:
As @aestrivex has mentioned, it is a way of writing 1.Even i encountered this
and it just means y=y-1 because
7&(-7) is x00000111 & x11111001 = x00000001 = 1
I believe it is a trick to figure out if n is a power of 2. (n == (n & -n)) IFF n is a power of 2 (1,2,4,8).
It's an old trick that gives a number with a single bit in it, the bottom bit that was set in
n
. At least in two's complement arithmetic, which is just about universal these days.The reason it works: the negative of a number is produced by inverting the number, then adding 1 (that's the definition of two's complement). When you add 1, every bit starting at the bottom that is set will overflow into the next higher bit; this stops once you reach a zero bit. Those overflowed bits will all be zero, and the bits above the last one affected will be the inverse of each other, so the only bit left is the one that stopped the cascade - the one that started as 1 and was inverted to 0.
P.S. If you're worried about running across one's complement arithmetic here's a version that works with both: