Check whether the unsigned integer is a power of 2 in a row of C expressions.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.