Function to find the given number is a power of 2 or not?

Answer Posted / hassan noureddine

To be a power of 2 number,is to have a single 1 bit, and the
rest bits are zeros, lik2 1, 2, 4 , 8, 16, 32, 64, 128, ...

the bitsize of the number is sizeof(number) * 8

isPowerOf2() returns 1 if successful, or 0 (false) otherwise
int isPowerOf2 (number)
{
int foundOnes = 0;
int bitsize = sizeof(number) * 8;

for (i = 0; i < bitsize; i++)
{
if (number & 1)
{
if(++foundOnes > 1)
return false;
/* shift the number to the right */
number >> 1;
}
}
return foundOnes;
}

Is This Answer Correct ?    20 Yes 12 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Why is c fast?

609


Difference between malloc() and calloc() function?

655


How can a number be converted to a string?

608


Explain how can I prevent another program from modifying part of a file that I am modifying?

642


The difference between printf and fprintf is ?

720






Explain what are linked list?

626


main() { inta=10,b=20; a>=5?b=100:b=200; printf("%d ",b); }

914


To print the pattern 1 2 3 4 5 10 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9

2191


Is null always defined as 0(zero)?

616


Is there anything like an ifdef for typedefs?

704


Is javascript based on c?

595


How to set file pointer to beginning c?

671


What is an auto variable in c?

758


What are c preprocessors?

680


How can you increase the size of a statically allocated array?

619