位运算的一些总结

来源:互联网 发布:money理财通mac版 编辑:程序博客网 时间:2024/05/01 19:03

C语言中有关位运算的操作符按照优先级排列一共有:

~:按位取反;

<<,>>:左移与右移;

&:按位与;

^:按位异或;

|:按位或;

比如对两个数进行交换的时候可以采用swap进行操作,求平均值可以采用average函数操作:

#include<stdio.h>#include<stdlib.h>#include<string.h>typedef unsigned int type;void swap(type *a,type *b){(*a)=(*a)^(*b);(*b)=(*b)^(*a);(*a)=(*a)^(*b);}type average(type a,type b){    return (a&b) + ((a^b)>>1);}int main(){    type a=0xffffff03;type b=0x44223323;type c=0x12;type d=0x34;printf("a=%#x;b=%#x\n",a,b);swap(&a,&b);printf("a=%#x;b=%#x\n",a,b);printf("average:%#x\n",average(d,c));}
结果如下:


当然上面只是位运算的一些示例,其它的用法非常之多,这需要深入学习。

0 0
原创粉丝点击