/* filename : wb.c */#include<stdio.h>/* get bits */voidget_bits(void){char x =0X5B;//#b 0101 1010char f =0X0F;//#b 0000 1111char c = x & f;//#b 0000 1010printf("Char x : [0X%02X]\n", x);printf("Char f : [0X%02X]\n", f);printf("bit AND ----------\n");printf("Result : [0X%02X]\n", c);}/**/intmain(int argc,char*argv[]){get_bits();return0;}//----- ~&|^ -----//
6、编译运行,输出结果如下:
达到预期,0x5B的后四位B保留了下来!
Char x :[0X5B]
Char f :[0X0F]
bit AND ----------
Result :[0X0B]
7、设置字节的某些位
按位或某个数,相当于加上某个数,如按或0x06,相当于加上0x06,测试代码如下:
/* set bits */voidset_bits(void){char x =0X30;//#b 0011 0000char f =0X06;//#b 0000 0110char c = x | f;//#b 0011 0110printf("Char x : [0X%02X]\n", x);printf("Char f : [0X%02X]\n", f);printf("bit OR ----------\n");printf("Result : [0X%02X]\n", c);}
8、编译运行,输出结果如下:
达到预期,0x30的后四位加上了一个6!
Char x :[0X30]
Char f :[0X06]
bit OR ----------
Result :[0X36]
9、按位异或常用来交换两个变量的值
两个数进行两次异或操作,就能达到交换两个数的值的效果,代码如下:
/* swap a, b */voidtest_swap(void){char a =0X70;//#b 0111 0000char b =0X07;//#b 0000 0111printf("before swap => a : [0X%02X], b : [0X%02X]\n", a, b);
a = a ^ b;//#b 0111 0111
b = b ^ a;//#b 0111 0000
a = a ^ b;//#b 0000 0111printf(" after swap => a : [0X%02X], b : [0X%02X]\n", a, b);}
10、编译运行,输出结果如下:
达到预期,a和b的值交换了!
before swap => a :[0X70], b :[0X07]
after swap => a :[0X07], b :[0X70]
11、完整代码如下:
/* filename : wb.c */#include<stdio.h>/* swap a, b */voidtest_swap(void){char a =0X70;//#b 0111 0000char b =0X07;//#b 0000 0111printf("before swap => a : [0X%02X], b : [0X%02X]\n", a, b);
a = a ^ b;//#b 0111 0111
b = b ^ a;//#b 0111 0000
a = a ^ b;//#b 0000 0111printf(" after swap => a : [0X%02X], b : [0X%02X]\n", a, b);}/* set bits */voidset_bits(void){char x =0X30;//#b 0011 0000char f =0X06;//#b 0000 0110char c = x | f;//#b 0011 0110printf("Char x : [0X%02X]\n", x);printf("Char f : [0X%02X]\n", f);printf("bit OR ----------\n");printf("Result : [0X%02X]\n", c);}/* get bits */voidget_bits(void){char x =0X5B;//#b 0101 1010char f =0X0F;//#b 0000 1111char c = x & f;//#b 0000 1010printf("Char x : [0X%02X]\n", x);printf("Char f : [0X%02X]\n", f);printf("bit AND ----------\n");printf("Result : [0X%02X]\n", c);}/**/intmain(int argc,char*argv[]){test_swap();//set_bits ();//get_bits ();return0;}//----- ~&|^ -----//