什么是按位XOR(异或)是什么意思? [英] What does bitwise XOR (exclusive OR) mean?

查看:2252
本文介绍了什么是按位XOR(异或)是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解C#或一般的二元运算符,特别是 ^ - 异或

I'm trying to understand the binary operators in C# or in general, in particular ^ - exclusive or.

例如:

鉴于正整数的数组。所有数字发生偶数次除了发生奇数倍一个号码。查找O(n)时间和恒定空间的数量。

Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time and constant space.

这是可以做到的^如下:是否所有元素的按位异或。最终我们得到它具有奇数出现的次数。

This can be done with ^ as follows: Do bitwise XOR of all the elements. Finally we get the number which has odd occurrences.

它是如何工作的?

当我做的:

int res = 2 ^ 3;  
res = 1;  
int res = 2 ^ 5;  
res = 7;  
int res = 2 ^ 10;  
res = 8;  

什么是实际发生的?有什么其他的魔法位?任何引用我可以查找和了解他们吗?

What's actually happening? What are the other bit magics? Any reference I can look up and learn more about them?

推荐答案

要看看它是如何工作的,首先你需要写二进制两个操作数,因为按位运算个别位工作。

To see how it works, first you need to write both operands in binary, because bitwise operations work on individual bits.

然后你可以将真值表为您的特定运营商。它作用于每对具有在两个操作数的同一位置(同一地点的值)位。因此, A的最左边位(MSB) B 的MSB相结合,产生结果的MSB。

Then you can apply the truth table for your particular operator. It acts on each pair of bits having the same position in the two operands (the same place value). So the leftmost bit (MSB) of A is combined with the MSB of B to produce the MSB of the result.

例如: 2 ^ 10

    0010 2
XOR 1010 8 + 2
    ----
    1    xor(0, 1)
     0   xor(0, 0)
      0  xor(1, 1)
       0 xor(0, 0)
    ----
 =  1000 8

和结果是8。

这篇关于什么是按位XOR(异或)是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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