XOR 运算符 - 它是如何工作的? [英] XOR Operator - How does it work?

查看:46
本文介绍了XOR 运算符 - 它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能用简单的英语解释一下什么是 XOR (^) 运算符以及它在以下代码中的作用:

Can you please explain me in plain English what is the XOR (^) operator and what it does in the following code:

public int GetHashCode(Box bx)
{
    int hCode = bx.Height ^ bx.Length ^ bx.Width;
    return hCode.GetHashCode();
} 

推荐答案

XOR 代表异或.它确保 A 或 B 为真,但永远不会同时为真.在这种情况下,我们正在执行按位运算,因此您可以制作一个漂亮的小结果图,如下所示;

XOR stands for exclusive or. It ensures that either A or B is true but never both. In this case we're doing a bitwise operation so you can make a nice little graph of the outcomes, they are as follows;

0 ^ 1 = 1
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 0 = 0

由于您将其应用于整数,因此上述结果应用于操作数中的每一位.因此,假设您的高度、长度和宽度分别为 1、2、3.

Since you're applying it to integers the above outcomes are applied to each bit in the operands. So lets just say you have the values 1, 2, 3 for height, length, and width respectively.

你首先会

0001 ^ 0010 导致 0011 那么这将被异或到 3 所以 0011 ^ 0011 给你 0000

0001 ^ 0010 resulting in 0011 then that would be XOR'd into 3 so 0011 ^ 0011 which gives you 0000

提供评论中的维基链接以补充我的解释;http://en.wikipedia.org/wiki/Exclusive_or#Computer_science

supplying the wiki link from the comments to supplement my explanation; http://en.wikipedia.org/wiki/Exclusive_or#Computer_science

为什么 0001 ^ 0010 导致 0011?

所以最好一点一点地做.想想运算符迭代两组位并比较它们的对.所以在这种情况下,让我们从右到左工作(在这种情况下从最不重要到最重要).

So it's best to do this bit by bit. Think of the operator iterating over the two sets of bits and comparing pairs of them. So in this case lets work from right to left (least significant to most in this case).

1 ^ 0 = 1 // xxx1
0 ^ 1 = 1 // xx11
0 ^ 0 = 0 // x011
0 ^ 0 = 0 // 0011  - end of input

把它们拼凑起来,你会得到 0011.基本上,获取每对输入并参考结果的真值表.注释显示输出,x 是一个尚未计算的值.

so piecing that back together you get 0011. Basically, take each pair of inputs and reference the truth table for the outcome. The comment shows the output with x being a value that has not yet been calculated.

关于碰撞,是的,在这种情况下有很多碰撞.如果我说它是独一无二的,那是一个糟糕的词选择.我真正的意思是,如果你有 2、8、4 作为你的值,按照这个顺序对它们进行异或将总是产生相同的值.

With regard to collisions, yes, in this case there are plenty of collision. If I said it would be unique that was a poor word choice. What I really mean is that if you have 2, 8, 4 as your values XOR'n them in that order will always produce the same value.

这篇关于XOR 运算符 - 它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆