unexpected output :S

Hello World,

i have the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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.

Thank you.
Last edited on
2^j
What do you think the ^ operator does?

http://www.cplusplus.com/doc/tutorial/operators/
Why do you use bitwise XOR operator '^' ??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <math.h>


int main(void){
	int num = 3;
	int flag = 0;
	for(int j=1; j<=10; j++){
		if(num == (int)pow(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;
}
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.
oh, Thanks, i was totally stucked. I had used the ^ to be the exponential operator for ...Matlab ! But, this is C++ !!!


Thank you very much .
Topic archived. No new replies allowed.