C位运算中 异或运算符的 几点注意与示例

版权声明:本文为博主原创文章,欢迎转载,但请标出本文的出处,谢谢!欢迎访问本人的github主页【https://github.com/abodu】 https://blog.csdn.net/liudglink/article/details/44607229

C语言的 异或运算的 运算原理 应用。需要注意的是 位运算 是符合 交换律, 结合律 及 分配律的

/*
 * ====================================================================
 *           All Rights Reserved 2007-2015 CODD Orgnization
 * ====================================================================
 * Title: xor.c
 * Desp: sample of bit xor operation 
 * Author: Liu Dongguo(jealdean@outlook.com)
 * Verion: 1.0
 * Created: 03/24/2015 22:09:14 PM
 * ChgOn: 2015-03-25 01:06:45
 * ====================================================================
 */

////Principles
////P0  x^x=0
////P1  a^0=a
////P2  c=a^x ==> a=c^x (=a^x^x=a^0=a)
#include <stdio.h> 
int main (int argc, char* argv[])
{
	////sample1 :swap two values 
	int a=3;
	int b=517;
	printf("before swap:a=%d,b=%d\n",a,b);
	a^=b^=a^=b;
	printf("after swap:a=%d,b=%d\n",a,b);
	////samplp2: letter lowercase --> UPPERCASE
	int cMask='a'^'A';
	char c='b';
	printf("%c-->%c\n",c,c^cMask);
	////sample3: test Law of distribution
	if(12^22==(12^19+12^3))
	{
		printf("yes,xor obey Law of distribution\n");
	}
	return 0;
}


展开阅读全文

没有更多推荐了,返回首页