位操作运算
来源:互联网 发布:单片机c语言入门 编辑:程序博客网 时间:2024/05/21 12:39
前些天遇到一段关于c语言位运算的代码。
英文原文如下:
As an illustration of some of the bit operators, consider the function getbits(x,p,n) that returns the (right adjusted) n-bit
field of x that begins at position p. We assume that bit position 0 is at the right end and that n and p are sensible positive
values. For example, getbits(x,4,3) returns the three bits in positions 4, 3 and 2, right-adjusted.
/* getbits: get n bits from position p */
unsigned getbits(unsigned x, int p, int n)
{
return (x >> (p+1-n)) & ~(~0 << n);
}
The expression x >> (p+1-n) moves the desired field to the right end of the word. ~0 is all 1-bits; shifting it left n positions
with ~0<<n places zeros in the rightmost n bits; complementing that with ~ makes a mask with ones in the rightmost n bits.
~(~0 << n)等价于2^0+2^1+2^2+...+2^n。
return (x >> (p+1-n)) & ~(~0 << n)
此代码的功能为:返回x中从右边数,第p位开始,向右数n位的字段。
test code:
#include<stdio.h>//unsigned getbits(int x,int p,int n)getbits(int x,int p,int n){unsigned a; //return a=(x>>(p+1-n))&~(~0<<n);//返回x中从右边数,第p位开始,向右数n位的字段 a=((x>>(p+1-n))&~(~0<<n));//x>>(p+1-n):x右移(p+1-n)位,~0左移n位printf("%x\n",0x00000000<<n);// printf("%x\n",0xffffffff<<n);//printf("%x\n",(~0<<n));//printf("%x\n",~0);//printf("%x\n",~(~0<<n));//printf("%x\n",x>>(p+1-n)); printf("%u\n",a);}int main(int argc,char* argv[]){ getbits(137,4,1);return 0;}
之前手工检测时的结果总是和运行结果不一致,后来发现,是由于没注意到"We assume that bit position 0 is at the right end ".一定要注意下标啊!
- [POJ3748]位操作[位运算]
- 位运算操作
- 位运算操作符
- 位运算操作符
- 位操作运算
- 位运算小结操作
- 位运算操作相关
- 按位操作运算
- Java位操作运算
- 位操作运算
- 位运算符操作
- 位运算符操作
- 位运算操作相关
- 位操作运算符
- 位操作运算符
- 位操作运算符
- 位运算操作
- JAVA<位操作运算>
- 构成逆序对
- IOS5 ARC unsafe_unretained等说明
- UpdatePanel控件的使用
- MyEclipse 配置 Hadoop 插件
- 多用户(windows)远程登录ubuntu 10.04 解决方案
- 位操作运算
- hadoop命令
- ssh免账号登陆
- VB工程---百例46-----园、椭圆、饼形(2)
- 我开发的LevelGenerator 一键创建多个楼层的插件发布了,公开源代码
- SVN的Peg Revision和Operative Revision
- exosip库
- 中文分词技术
- 经验