位操作运算

本文深入探讨了C语言中位运算的应用,并详细解释了一个用于获取特定位段的函数getbits的原理与实现过程。通过实例演示,帮助读者掌握如何通过位操作获取目标数据段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     前些天遇到一段关于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 ".一定要注意下标啊!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值