Determines whether the value is a power of 2.

Source: Internet
Author: User

Judge whether a value is a power of 2. Common functions in 3D games

In the past, the judgment method was to cyclically determine bits or directly divide them continuously.

The efficiency of these methods can be imagined.

 

Here I use a direct bit operation to get the efficiency of the Code. first look at the Code:

  1. Bool Is2Power (int n)
  2. {
  3. If (n = 1)
  4. Return false;
  5. If ((((~ N) & (n-1) + 1) = n)
  6. Return true;
  7. Return false;
  8. }

Let's explain (n = 512 is used as an example ):

1. Dimension 1 is not a power of 2

2. Inverse n (~ N) the result is 0 xfffffdff, indicating that the highest bit of 512 is 0, and the other bit is 1.

3. The n-1 result is 0x000001ff, indicating that the highest bit of 512 and the highest bit are both 0, and the other bit is 1.

4. The power of all two is the highest bit. The other bit is 0.

 

As a result, we found that the n-1 result is that we want to get the valid bit value of this value.

In this way, we calculate ((~ N) & (n-1), a value without the highest bit is obtained, that is, (n-1) = 512-1 = 511.

Therefore, we get a new value equal to the value of 511 + 1.

And the new value is equal to the original value.

 

Test n = 500 again.

~ The n result is 0xfffffe0b, and the highest bit is 0. The other bit is not set to 1.

The n-1 result is 0x000001f3. The highest bit and the highest bit are both 0, and the other bit is not set to 1.

((~ N) & (n-1) the result is not the 499 we think of, but a result of bitwise AND.

So it is not equal to the original value.

 

Now, we have tested the function to determine whether the value is a power of 2.

How about it? Try it.

 

 

 

 

 

 

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.