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

What is the use of linkage in c language?

611


What is pre-emptive data structure and explain it with example?

3203


What is a ternary operator in c?

646


What is the difference between array and structure in c?

565


What is the sizeof () operator?

614






When is a void pointer used?

672


What does 4d mean in c?

932


What is a structure member in c?

536


how to write optimum code to divide a 50 digit number with a 25 digit number??

2743


why do some people write if(0 == x) instead of if(x == 0)?

648


What are the 5 types of inheritance in c ++?

574


Explain how can I avoid the abort, retry, fail messages?

583


What does emoji p mean?

593


What is the difference between pure virtual function and virtual function?

643


What is the difference between the local variable and global variable in c?

524