Oct 20, 2014 at 7:05pm UTC
What would the value of x be at the end of this snippet?
int x = 12;
x ^= 2;
And how did you get to your answer?
Last edited on Oct 20, 2014 at 7:13pm UTC
Oct 20, 2014 at 7:16pm UTC
run it and find out.
i got the last one by converting to binary first before or'ing.
Last edited on Oct 20, 2014 at 7:17pm UTC
Oct 20, 2014 at 7:26pm UTC
^ is the bit-wise xor operator. x ^= y
is equivalent to: x = x ^ y
.
That means that this code is equivalent to x = 12 ^ 2
Now we need a truth-table for xor:
0 xor 0 is 0
1 xor 0 is 1
0 xor 1 is 1
1 xor 1 is 0
12 in binary is 1100
2 in binary is 0010
So if we xor every bit we get:
1110
In decimal, that would be 14.
Last edited on Oct 20, 2014 at 7:33pm UTC
Oct 20, 2014 at 7:33pm UTC
OP why change your original question?
i won't do your homework for you. but it looks like stewbond will :)
Oct 20, 2014 at 9:18pm UTC
Thank you @Stewbond!
@mutexe I was just looking for a clear explanation of how xor works, and an example of how to do it on paper, I thought someone on here might be willing to explain it.