Determining whether a number is a power of 4 (may be a power of 2)

First determines whether a power of 2, 4 are power as a power of two
power of two num == 1, 2, 4, 8, 16, 32 ...
into hexadecimal i.e. 2: 1, 10, 100, 1000, 10,000, 100,000, ...
obviously it can be derived (num & (num)) == 0;

Power 4 num == 1, 4, 16, 64, ...
into a binary namely: 1, 100, 10000, 1000000, ...
apparent power can be derived in 4 binary "1" in an odd position, and determines the binary number "1" is in the position to use odd num & 0x55555555;
as 5 == 0x0101;
eight because 5 bits are 32-bit integers;

Development: Analyzing binary number "1" is to use the even-num & 0xaaaaaaaa position;
as a == 0x1010;

#include <stdio.h>
#include <stdlib.h>

#define True 1
#define False 0
int function( int num )
{
    if( num<0 || (num&(num-1))!=0 )
        return False;
        
   int aa = 0x55555555;
   
   if( num&aa )  
       return True;
   else
       return False;       
}

int main(void)
{
    int num = 100;
    int i;
    
    for( i=0; i<num; i++ )
    {
        if( function(i) )
            printf("%d ", i);
    }
    
    return 0;
}
Published 18 original articles · won praise 2 · Views 631

Guess you like

Origin blog.csdn.net/weixin_39618542/article/details/102150257