位操作运算

来源:互联网 发布:单片机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 ".一定要注意下标啊!