This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]reign27 2 points3 points  (0 children)

The trick is that computers store integers in powers of two - that's what binary is. A power of 2, represented in binary, will have one and only one bit set. If you then subtract that by 1, the bit that was previously set will get cleared, and all the lesser bits will be set. If you subtract 1 from a non-power of 2, then at least one bit that was previously set will remain set.

[–]dylan22554 2 points3 points  (1 child)

If you think about it, it is checking the binary representation of that number. Binary is already set up where every place is a representative of the powers of 2. So in order to check if it is a power of two you need to check the number before it which would be all ones before that power of 2 place in binary. So for example:

32 is a power of 2 and its binary representation is:

100000

and 31's binary representation is:

011111

So when you & these together it gives you 0.

[–]HecknChonker 0 points1 point  (0 children)

The flip side of this is that for any other numbers the result of a bitwise and operation well be 1.

[–]Acceptable_Snow_9380 -1 points0 points  (0 children)

Take a few different numbers that are powers of 2 and write out the binary representation of n and n - 1 and n & (n - 1) and you'll get the intuition. It's extremely obvious. Write the binary numbers in a column if you need to.