Give a one-line C
Expression to test whether
Unsigned int is a power of two.
Check whether an unsigned integer is a power of 2 using a single line of C expression (the power of 2 refers to the power of a positive integer of 2, such as, 16)
Answer:
(N & (n-1) = 0)
The answer is as follows:
The power of 2 is in the hexadecimal form of 1 followed by many 0, such
100
10000
1000000
If you see such a number, you can immediately determine it is.
N and n-1 are binary numbers like this:
01000000
00111111
We can see that the corresponding bits are always 0 and 1, so N & (n-1) must be 0
Some may think of an exception or, N ^ (n-1) must be all 1. If you think about it carefully, you will find that it is not possible. Adding zero in the previous step will lead to some zero in the previous step.
Now we can see that the power of 2 will be 0 for N & (n-1), so will other numbers be non-0?
Example: 10010
10010 // original number
10001 // subtract one from the original number
10000 // bitwise AND subsequent results
We can see that it is true that it is not 0.
So why?
As long as a binary number is the power of 2, 1 will reduce the number of digits by one. Any other number will not cause this decrease in the number of digits. That is, only a number in the form of 1000... 0 can reduce the number of digits by one. Therefore, the first 1 (high 1) of N will be dropped and changed to 0. The value of bitwise AND is 0. Otherwise, the highest bit must be 1, if 1 is included, the entire expression is not 0.