#include <stdio.h>
int main(void){
int num = 3;
int j=1;
int flag = 0;
for(j=1;j<10;j++){
if(num == 2^j){
flag = 1;
break;
}
}
if(flag == 0){
printf("The num must be : {2,4,8,16,32,64,128,256,512,1024}:\n\n");
return -1;
}else{
printf("OK !!!\n\n");
}
return 0;
}
and compile it using g++ . i want the num to be a number of the following 2,4,8,16,32,64,128,256,512 etc. However, i have num=3 and i receive :
OK !!!
It must be simply, but no way, i cant fix it.
ps. probably i should have written the post in beginners.
The ^ operator is not exponentiation in C++. It is bitwise exclusive or.
In line 8, you are doing an an exclusive or for each bit in 2 with the corresponding bit in j.
When j is 1, you will be performing a bitwise exclusive or on each of the bits of 2 (000...10) and j (000...01). The results of the bitwise or operations are 3 (000...11), which is equal to number.