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
Why is c fast?
Difference between malloc() and calloc() function?
How can a number be converted to a string?
Explain how can I prevent another program from modifying part of a file that I am modifying?
The difference between printf and fprintf is ?
Explain what are linked list?
main() { inta=10,b=20; a>=5?b=100:b=200; printf("%d ",b); }
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
Is null always defined as 0(zero)?
Is there anything like an ifdef for typedefs?
Is javascript based on c?
How to set file pointer to beginning c?
What is an auto variable in c?
What are c preprocessors?
How can you increase the size of a statically allocated array?