Check if a number is power of two using macro defined function:
#define IS_POWER_OF_TWO(x) ( !( (x) & ((x)-1) ) )
e.g.
i. 4 is power of 2 (2x2)
4 == 0000 0100 binary
4-1 = 3 == 0000 0011 binary
ANDED == 0000 0000
! == 1111 1111 == is a power of two
ii. 8 is power of 2 (2x2x2)
8 == 0000 1000 binary
8-1 = 7 == 0000 0100 binary
ANDED == 0000 0000
! == 1111 1111 == is a power of two
iii. 15 is NOT power of 2 ( 2x2x2 == 8, 2x2x2x2 == 16 which already passed 15)
15 == 0000 1111 binary
15-1 = 14 == 0000 1110 binary
ANDED == 0000 1110 ( ! will result 0 )
! == 0000 0000 == not a power of two number
e.g C codes
#include
#include
#define ISPOW2(x)
!((x)&((x-1)))
int main (int argc, char *argv[])
{
int i=0;
int res=0;
if ( argc < face="courier new" size="2">
{
printf("Not enough input arguments\n");
return -1;
}
i = atoi(argv[1]);
if ( (res=ISPOW2(i)) )
printf("Number %d is a power of 2.\n", i);
else
printf("Number %d is NOT a power of 2.\n", i);
printf ("res = %d\n", res);
return 0;
}
No comments:
Post a Comment