位操作运算

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

C#提供了许多位操作运算符,它们可以用于对二进制位进行操作,这些运算符包括: 1. 按位与(&):将两个操作数的每一位进行与运算,如果对应位都为1,则结果为1,否则为0。 示例代码: ``` int a = 5; // 二进制表示为 00000101 int b = 3; // 二进制表示为 00000011 int c = a & b; // c 的值为 00000001,即 1 ``` 2. 按位或(|):将两个操作数的每一位进行或运算,如果对应位都为0,则结果为0,否则为1。 示例代码: ``` int a = 5; // 二进制表示为 00000101 int b = 3; // 二进制表示为 00000011 int c = a | b; // c 的值为 00000111,即 7 ``` 3. 按位异或(^):将两个操作数的每一位进行异或运算,如果对应位相同,则结果为0,否则为1。 示例代码: ``` int a = 5; // 二进制表示为 00000101 int b = 3; // 二进制表示为 00000011 int c = a ^ b; // c 的值为 00000110,即 6 ``` 4. 按位取反(~):将操作数的每一位进行取反运算,即0变成1,1变成0。 示例代码: ``` int a = 5; // 二进制表示为 00000101 int b = ~a; // b 的值为 11111010,即 -6(注意这里是有符号的整数) ``` 5. 左移(<<):将操作数的所有位向左移动指定的位数,右侧用0填充。 示例代码: ``` int a = 5; // 二进制表示为 00000101 int b = a << 2; // b 的值为 00010100,即 20 ``` 6. 右移(>>):将操作数的所有位向右移动指定的位数,左侧用符号位填充(即如果操作数是正数,则左侧用0填充,如果是负数,则左侧用1填充)。 示例代码: ``` int a = 5; // 二进制表示为 00000101 int b = a >> 2; // b 的值为 00000001,即 1 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值