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 return type of main is not necessary in linux
Difference between strcpy() and memcpy() function?
Explain indirection?
What is || operator and how does it function in a program?
What does sizeof int return?
Explain what is the purpose of "extern" keyword in a function declaration?
Tell me what is the purpose of 'register' keyword in c language?
Explain output of printf("Hello World"-'A'+'B'); ?
What are register variables? What are the advantage of using register variables?
Which is better between malloc and calloc?
What is optimization in c?
while initialization of array why we use a[][2] why not a[2][]...?
What are the back slash character constants or escape sequence charactersavailable in c?
What is a null pointer in c?
What is the right type to use for boolean values in c? Is there a standard type?