首页 > 代码库 > c语言setbits,invert

c语言setbits,invert

k&r习题2-6,setbits(x,p,n,y),将x中从第p位开始的n个二进制位设置为y中最右边n位的值,x的其余各位保持不变。

#include<stdio.h>

unsigned setbits(unsigned x, int p, int n,unsigned y)
{
    int mask;
    int pos=p+1-n;
    mask=~(~0<<n) << pos ;
    x=x & ~mask;
    y=y<<pos & mask;
    x=x|y;
    
    return x;
}

main()
{
    int x=012;
    int y=077;
    printf("%o\n",setbits(x,4,3,y));
}



~0的所有位都为1,通过对其移位补0,建立屏蔽码,在位操作中很常用

2-7,invert(x,p,n)

#include<stdio.h>
unsigned invert(unsigned x, int p, int n)
{
    return x^(~(~0<<n) << (p+1-n));
}

int main()
{
    unsigned a=034;
    printf("%o\n",invert(a,4,3));
}



与1按位异或,原位反转;与0异或,原位不变

c语言setbits,invert