Obtains the power of 2 with the smallest value greater than N.

Source: Internet
Author: User
Isn't it easy?
To determine whether a number N is a power of 2, you only need to check whether N & (n-1) is 0.
To find the power of 2 that is larger than it, You can first fill the highest one of it with 1 and then add 1.
The filling method can be log32 = 5 times by bit or. In this way, branches do not have to be judged.
Maybe there is a faster and better way.

# Include < Cstdio >
Inline Bool Is_power_of_2 ( Int N)
{
Return(N&(N-1))= 0;
}
Inline Int Min_power_of_2_g ( Int N)
{
// Return n | = n> 16, N | = n> 8, N | = n> 4, N | = n> 2, N | = n> 1, n + 1; it is actually the same, it looks shorter.
Return (N | = N > 16 ) | = N > 8 ) | = N > 4 ) | = N > 2 ) | = N > 1 , N +   1 ;
}
Inline Int Min_power_of_2_eg ( Int N)
{
If(Is_power_of_2 (n ))
ReturnN;
ReturnMin_power_of_2_g (N );
}

Int Main ()
{
Int N;
While (Scanf ( " % D " , & N) =   1 )
{
N=Min_power_of_2_eg (N );
Printf ("% X % d \ n", N, N );
}
Return   0 ;
}
/**/ /* Here is the code generated by vc6 release:
MoV ECx, dword ptr [esp]; fetch n
MoV eax, ECx
Lea edX, [ecx-1]; n-1
Test ECx, EDX; n (n-1)
Je end1
SAR eax, 10 h; n | = n> 16
Or eax, ECx
MoV ECx, eax
SAR ECx, 8; n | = n> 8
Or eax, ECx
MoV edX, eax
SAR edX, 4; n | = n> 4
Or eax, EDX
MoV ECx, eax
SAR ECx, 2; n | = n> 2
Or eax, ECx
MoV edX, eax
SAR edX, 1; n | = n> 1
Or eax, EDX
INC eax; Add 1
End1:
*/

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.