Ank*_*ani 5 xor bitwise-operators
嘿,有人可以向我解释 XOR 运算符的意义是什么,以及我可以使用它解决什么问题。如果有人可以列出我们可以使用 XOR 运算符解决哪些类型的问题,那将非常有帮助。
提前致谢。
从 XOR 的真值表 (^) 开始:
x y x^y
0 0 0
0 1 1
1 0 1
1 1 0
Run Code Online (Sandbox Code Playgroud)
可以使用 XOR 解决的问题:
2 布尔函数x和y.
If x and y are same then x ^ y = 0
If x and y are different then x ^ y = 1
Run Code Online (Sandbox Code Playgroud)
查找字节或整数的二进制表示中的 1 ('1') 数是奇数还是偶数。
unsigned char a = 10; //in binary representation 00001010 (even number of 1s)
unsigned char b = 11; //in binary representation 00001011 (odd number of 1s)
Simply XORing all the bits will give:
* result = 1, if number of bits is odd
* result = 0, if number of bits is even
Run Code Online (Sandbox Code Playgroud)
使用{Point 2.}可以找到数据位的奇偶校验(Parity Bit)。
If even parity is required(i.e the data bits should have even number of 1s) then
if all the bits are XORed and if it gives the result 1 then
**Parity Bit = 1** else **Parity Bit = 0**.
Similar case can be made if odd parity of data bits are required.
Run Code Online (Sandbox Code Playgroud)
在命题逻辑中if and only if (shortened iff) is a biconditional logical connective,这iff可以使用XNOR或~XOR(即异或的否定)进行评估。
如果涉及2个布尔函数一个方程式A和B如{A'.B + A.B'}遇到然后这个方程简化为A ^ B。解决{A'.B + A.B'}使用原语运算符(AND(。),OR(+)和反('))将导致5操作,这些操作可以使用减少到1个操作XOR(^)。只是因为A^B = A'.B + A.B'. 如果所遇到的方程是{A'B' + AB}然后{A'B' + AB}= ~XOR(即XNOR或XOR的否定)。
如果数据中的某个特定位需要反转(即 1 到 0 或 0 到 1),那么简单地对该位进行异或1就可以达到目的。
data = 1010;
^^^^
0001 (inverting the LSB, first bit from right)
---------------
result = 1011
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1368 次 |
| 最近记录: |