x^=2;


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
run it and find out.
i got the last one by converting to binary first before or'ing.
Last edited on
^ 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
OP why change your original question?
i won't do your homework for you. but it looks like stewbond will :)
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.
Topic archived. No new replies allowed.