In binary representation, a number is power of two if it has only one on bit and others bits as off.
For ex: binary representation of 8 is 1000 (contains only one on bit) whereas, that of 5 is 0101(contains two on bits).
If a number is power of two, for example 8, bitwise and of 8 and 7 is 0
Code:
#include <stdio.h>
int main(){
int n = 8;
if((!(n & (n-1)))){ // & is bitwise and whereas ! is logical not
printf("The number is power of two\n");
}else{
printf("Not a power of two\n");
}
return 0;
}
However, this does not give correct result for n = 0. For n = 0, the above expression would be 1, thus printing, "the number is power of two". To accommodate, the case for n = 0, use the following code.
#include <stdio.h>
int main(){
int n = 8;
if((n && !(n & (n-1)))){ // && is logical and, ! is logical not and & is bitwise and
printf("The number is power of two\n");
}else{
printf("Not a power of two\n");
}
return 0;
}
For ex: binary representation of 8 is 1000 (contains only one on bit) whereas, that of 5 is 0101(contains two on bits).
If a number is power of two, for example 8, bitwise and of 8 and 7 is 0
Code:
#include <stdio.h>
int main(){
int n = 8;
if((!(n & (n-1)))){ // & is bitwise and whereas ! is logical not
printf("The number is power of two\n");
}else{
printf("Not a power of two\n");
}
return 0;
}
However, this does not give correct result for n = 0. For n = 0, the above expression would be 1, thus printing, "the number is power of two". To accommodate, the case for n = 0, use the following code.
#include <stdio.h>
int main(){
int n = 8;
if((n && !(n & (n-1)))){ // && is logical and, ! is logical not and & is bitwise and
printf("The number is power of two\n");
}else{
printf("Not a power of two\n");
}
return 0;
}