C语言中的XOR运算符

Stackoverflow上一个回答很好地解释了XOR运算符的作用:

If you know how XOR works, and you know that ^ is XOR in C, then this should be pretty simple. You should know that XOR will flip bits where 1 is set, bits 2 and 5 of 0b00100100 are set, therefore it will flip those bits.

From an “during the test” standpoint, let’s say you need to prove this to yourself, you really don’t need to know the initial value of star to answer the question, If you know how ^ works then just throw anything in there:

 00100100
^10101010  (star's made up value)
---------
 10001110  (star's new value)

 bit position: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0  
   |---|---|---|---|---|---|---|---
 star's new v: | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0
   |---|---|---|---|---|---|---|---
 star's old v: | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0

总结一下,就是第二个操作数用来控制第一个操作数:第二个操作数中bit1会导致第一个操作数中相应的bit发生反转,而bit0则会让第一个操作数中相应的bit不变。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.