有关如何使用按位运算符交换两个数字的说明? [英] Explanation about how to swap two numbers using bitwise operator?
问题描述
#include< iostream>
使用 命名空间标准;
int main()
{
int a,b;
cout<< 输入两个数字<< endl;
cin>> a>> b;
cout<< 原始值<< a<< \t<< b<< endl;
a = a ^ b;
b = a ^ b;
a = a ^ b;
cout<< 交换<< a<<< \t<< b;
}
这里我们使用^(按位运算符)但我不能了解交换的确切过程。
任何人都可以告诉我这个过程是如何工作的?
^是一个异或 - 每个结果当且仅当位不同时,与另一位进行异或运算。
将它全部扩展到几代人中并且非常明显:
a1 = a0 xor b0
b1 = a1 xor b0
a2 = a1 xor b1
代替a1,然后b1:
a1 = a0 xor b0
b1 =(a0 xor b0)xor b0
a2 =(a0 xor b0)xor((a0 xor b0)xor b0)
因为XOR完全关联且可交换,所以我们可以将括号移动
b1 = a0 xor(b0 xor b0)
a2 =((a0 xor a0)xor(b0 xor b0))xor b0
由于x xor x
对于任何x总是为零,
b1 = a0 xor 0
a2 =(0 x或0)xor b0因为
x xor 0
对于x的任何值总是x:
b1 = a0
a2 = b0
交换已完成。
如果没有复杂的公式,只需记住 xoring两次对相同的值给出起始值。
b = a ^ b
,在a = a ^ b
之后,实际上使b = a ^ b ^ b
(这只是a
)。
现在,a = a ^ b
,b
只需a
和a
只需a ^ b
,使a = a ^ b ^ a
,这只是b
。
这相对简单。 ^运算符是XOR(异或)运算符,表示:
100 ^ 101 = 001,例如关键是,只有两位不同,结果才是1.
现在看看会发生什么:
a = a ^ b;
b = a ^ b;
这是一样的:
b =(a ^ b)^ b;
这是相同的喜欢:
b = a ^(b ^ b);
b ^ b总是为空(根本没有不同的位),所以b = a!
同样的是最后:
a =(a ^ b)^(a ^ b)^ b;
a =(a ^ a)^(b ^ b)^ b;
a = b;
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter two number"<<endl;
cin>>a>>b;
cout<<"Original value "<<a<<"\t"<<b<<endl;
a=a^b;
b=a^b;
a=a^b;
cout<<"After swaping "<<a<<"\t"<<b;
}
Here we have use ^ (bitwise operator) but I can't understand the exact process of swapping.
Anybody can tell me how this process work?
^ is an XOR - the result of each bit XORed with another bits is one if and only if the bits are different.
Expand it all out into the generations and it's pretty obvious:
a1 = a0 xor b0 b1 = a1 xor b0 a2 = a1 xor b1
Substituting for a1, then b1:
a1 = a0 xor b0 b1 = (a0 xor b0) xor b0 a2 = (a0 xor b0) xor ((a0 xor b0) xor b0)
Because XOR is fully associative and commutative we can move the brackets round
b1 = a0 xor (b0 xor b0) a2 = ((a0 xor a0) xor (b0 xor b0)) xor b0
Sincex xor x
is always zero for any x,
b1 = a0 xor 0 a2 = (0 xor 0) xor b0And since
x xor 0
is always x for any value of x:
b1 = a0 a2 = b0
And the swap is done.
Without complex formulas, just remember that xoring twice against a same value gives the starting value back.
b=a^b
, aftera=a^b
, in fact makesb=a^b^b
(that's justa
).
Now,a=a^b
, beingb
justa
anda
justa^b
, makesa=a^b^a
, that's justb
.
This is relatively simple. The ^operator is the XOR (exclusive OR) operator, that means:
100^101 = 001 e.g. The point is, only if two bits are different, the result is 1.
Now look what comes here:
a=a^b; b=a^b;
This is the same like:
b = (a^b)^b;
And this is the same like:
b = a^(b^b);
The b^b is always null (no different bits at all), so b = a!
The same is with a in the end:
a = (a^b)^(a^b)^b; a = (a ^ a) ^ (b ^b ) ^b; a = b;
这篇关于有关如何使用按位运算符交换两个数字的说明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!