C语言运算符之四

位运算的综合应用:
①数据合成   <<    |
将两个8位的数据合成一个16的数据
unsigned char a = 10;
unsigned char b = 15;
unsigned short c;
c = (a << 8)| b; 
将四个8位的数据合成一个32位的数据    
unsigned char a ;
unsigned char b ;
unsigned char c ;
unsigned char d ;
unsigned int f;
f = (a << 24)  | (b << 16) | (c << 8) | (d << 0)
将三个8位的数据合成一个数据    
unsigned char a ;
unsigned char b ;
unsigned char c ;
f = (a << 16) | (b << 8) | (c << 0)
---------------------------------------------    
②操作寄存器的形式
-------------------------------------
例子1:
unsigned int a;
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
&   11111111111111111111111111110111
 ~   00000000000000000000000000001000
<<  00000000000000000000000000000001
-----------------------------------        
xxxxxxxxxxxxxxxxxxxxxxxxxxxx0xxx
 a = a & (~(1 << 0))
公式:如果需要某个变量的二进制的某一个位变为0,其他位不变
找十进制数据1  
 a = a &~(1 << x)
说明: a:要操作的变量 
x:要操作的位号 
---------------------------------------- 
例子2:unsigned int a;
xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
| 0000 0000 0000 0000 0000 0000 0000 0001
xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxx1
a = a | (1 << 0)
xxxx xxxx xxxx xxxx xxxx xxxx xxxx x1xx
a = a |( 1 << 2)        
公式:如果需要对某个数据的二进制的某一个位置1,其他位保持不变
a = a |(1 << x)
说明: a:要操作的数据  
x:要操作位号                              
------------------------------------------------------    、
例子3:unsigned int a;
xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
& 1111 1111 1111 1111 1111 1111 1111 1100
~ 0000 0000 0000 0000 0000 0000 0000 0011
xxxx xxxx xxxx xxxx xxxx xxxx xxxx xx00
a = a & ~(3 << 0)    
xxxx xxxx xxxx xxxx xxxx xxxx xxxx x00x
a = a & ~(3 << 1)
公式:如果需要对某个数据的二进制的某两位写0,其他位不变,
找十进制数据3   
a = a &~(3 << x)               
说明: a:要操作的数据  
x:要操作位号              
例子4:unsigned int a;
xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
& 1111 1111 1111 1111 1111 1111 1111 1100
~    0000 0000 0000 0000 0000 0000 0000 0011       
xxxx xxxx xxxx xxxx xxxx xxxx xxxx xx00
|  0000 0000 0000 0000 0000 0000 0000 0010
xxxx xxxx xxxx xxxx xxxx xxxx xxxx xx10
a = a & ~(3 << 0)
a = a | (2 << 0)

xxxx xxxx xxxx xxxx xxxx xxxx xxxx x10x
a = a & ~(3 << 1);
a = a | (2 << 1);              
公式:
如果需要对某个数据的二进制的某两位操作,其他位不变
找十进制数据 3  
先将要操作的两位清零  
在或上具体值
a = a &~(3 << x);  //清零  
a = a | (n << x);
说明:a:要操作的数据  
x:移动的位数   
n:  
01    1 
10    2 
11    3 
---------------------------------------------
公式:
    如果需要某个变量的某一位变为0,其他位不改变  bit
    a = a & ~(1 << x);
公式:
    如果需要某个变量的某一位变为1,其他位不改变
    a = a | (1 << x);
公式:
如果对某两位写入某个值,其他位不变,
一定要先清零两位
再或上具体值
a = a & ~(3<<x);     //清零
a = a | (n << x)
01     n:1
10     n:2
11     n:3

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值