Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The bitwise XOR operator (^) is a binary operator that compares the corresponding bits of two operands and returns a new value where each bit is set to 1 if the corresponding bits of the operand are different, and 0 if they are the same.

You may also think about XOR in a following way:

Any “1” in B flips (inverts) the corresponding bit in A.

It’s like a vectorized NOT operation for single bits. Also works the other way (xor is commutative, A^B === B^A). This way of thinking is helpful when you see expressions like:

  X ^ (1 << 3)
  X ^ 8
  X ^ 0b1000
Which means “X with bit 3 flipped”. (3 means 4th from the right, as in …3210).


Xor is also equivalent to adding without propagating the carry.

  Ob010 + 0b011 = 0b101 (carry is propagated to the 3rd bit)
  0b010 ^ 0b011 = 0b001 (same result with no carry)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: