一、取反 ~
#include<stdio.h> #include<stdlib.h> void main(){ unsigned char ch=15; //0000 1111 char的单位是字节,1B=8bit,所以是8位 unsigned char fch=~ch; //1111 0000 取反 unsigned char ffch=~fch;//0000 1111 printf("%d,%d,%d ",ch,fch,ffch); system("pause"); }
注意:取反运算符不改变操作数的值,赋值运算符才会改变。
二、与运算 &
#include<stdio.h> #include<stdlib.h> //位与 1,1->1 01,10,00->0 //1&0=0 , 0&0=0 ->清零 //1&1=1 ,0&1=0 ->保留某些位不变 void main0(){ unsigned char ch1=3; //0000 0011 unsigned char ch2=240; //1111 0000 unsigned char ch3=255; //1111 1111 printf("%d ",ch1&ch2); //0000 0000 0 printf("%d ",ch1&ch3); //0000 0011 3 printf("%d ",ch2&ch3); //1111 0000 240 system("pause"); } //位与实现按位清零 void main1(){ unsigned char ch1=255; //1111 1111 unsigned char ch2=15; //0000 1111 unsigned char ch3=240; //1111 0000 printf("%d ",ch1&ch2); //清零高四位 printf("%d ",ch1&ch3); //清零低四位 printf("%d ",ch1&0); //全部清零 system("pause"); } //位与实现取出指定位 void main(){ unsigned char ch=169; //1010 1001 unsigned char ch1=60; //0011 1100 //0010 1000 40 printf("%d ",ch&ch1); //取出中间四位 system("pause"); }
三、或运算 |
#include<stdio.h> #include<stdlib.h> //位或运算 1|1=1 1|0=1 0|1=1 0|0=0 void main0(){ unsigned char ch=169; //1010 1001 unsigned char ch1=240; //1111 0000 //1111 1001 249 printf("%d ",ch|ch1); system("pause"); } //位或运算符可以让某些位变成1 1|0 = 1|1 =1 // 0|1=1 0|0=0 与0相或不改变 void main(){ unsigned char ch=169; //1010 1001 unsigned char ch1=15; //0000 1111 //1010 1111 实现低四位全部变1 printf("%d ",ch|ch1); system("pause"); }
四、异或运算 ^(相同为0,相异为1)
不借助中间变量,实现两变量交换值
#include<stdio.h> #include<stdlib.h> //异或 1^1=0 1^0=1 0^1=1 0^0=0 void main0(){ unsigned char ch1=169; //1010 1001 unsigned char ch2=15; //0000 1111 //1010 0110 166 printf("%d ",ch2^ch1); system("pause"); } //异或可以实现反转 void main1(){ unsigned char ch1=169; //1010 1001 unsigned char ch2=255; //1111 1111 全部反转 //0101 0110 86 printf("%d ",ch2^ch1); system("pause"); } void main2(){ unsigned char ch1=169; //1010 1001 unsigned char ch2=60; //0011 1100 指定位反转(中间反转) //1001 0101 149 printf("%d ",ch2^ch1); system("pause"); }
//异或交换两个变量 //不借助中间变量,实现两个变量的交换——>面试和嵌入式开发 //x,y交换值 x=x^y;y=x^y;x=x^y /* 等同于加减法实现交换值 x=20,y=10; x=x+y; //x=30,y=10 y=x-y; //x=30,y=20 x=x-y; //x=10,y=20 */ void main(){ unsigned char ch1=20; //0001 0100 unsigned char ch2=10; //0000 1010 printf("%d,%d ",ch1,ch2); ch1=ch1^ch2; ch2=ch1^ch2; ch1=ch1^ch2; printf("交换之后%d,%d ",ch1,ch2); system("pause"); }
五、位运算总结
#include<stdio.h> #include<stdlib.h> void main(){ unsigned char ch1=168; //1010 1000 unsigned char ch2=133; //1000 0101 printf("&与:%d ",ch1&ch2); //1000 0000 128 printf("|或:%d ",ch1|ch2); //1010 1101 173 printf("^异或:%d ",ch1^ch2); //0010 1101 45 unsigned char ch3=~ch1,ch4=~ch2; printf("~反:%d,%d %d,%d ",ch3,ch4,~ch1,~ch2); system("pause"); }