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
What is the use of linkage in c language?
What is pre-emptive data structure and explain it with example?
What is a ternary operator in c?
What is the difference between array and structure in c?
What is the sizeof () operator?
When is a void pointer used?
What does 4d mean in c?
What is a structure member in c?
how to write optimum code to divide a 50 digit number with a 25 digit number??
why do some people write if(0 == x) instead of if(x == 0)?
What are the 5 types of inheritance in c ++?
Explain how can I avoid the abort, retry, fail messages?
What does emoji p mean?
What is the difference between pure virtual function and virtual function?
What is the difference between the local variable and global variable in c?