k&r习题2-6,setbits(x,p,n,y),将x中从第p位开始的n个二进制位设置为y中最右边n位的值,x的其余各位保持不变。
#include
unsigned setbits(unsigned x, int p, int n,unsigned y)
{
int mask;
int pos=p+1-n;
mask=~(~0<
x=x & ~mask;
y=y<
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
unsigned invert(unsigned x, int p, int n)
{
return x^(~(~0<
}
int main()
{
unsigned a=034;
printf("%o\n",invert(a,4,3));
}
与1按位异或,原位反转;与0异或,原位不变
原文:http://my.oschina.net/sukai/blog/312090