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

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;
}

评论

暂无评论