【发布时间】:2013-06-27 04:26:58
【问题描述】:
我遇到了一个问题: “练习 2-6。编写一个函数 setbits(x,p,n,y),它返回 x 的 n 位开始于 位置 p 设置为 y 的最右边 n 位,其他位保持不变。"
我为此编写了一个函数,如下所示。这按预期工作。
int func_setx(int x,int p,int n,int y)
{
int a_t= ~0 << (p+n);
int b_t= ~a_t >> n;
int x_t= x& (a_t | b_t); // a temporary x which has the bits to be changed as 0 , rest of the bits unchanged.
int mask= (y << p) & (~(~0 << (p+n))); // a mask which has required bits from y in positions to be set , rest all bits 0.
printf("\nCheckpoint : mask= %x x_t= %x\n",mask,x_t);
int result= mask|x_t;
return result;
}
但是不知怎么感觉逻辑很长,可以优化,但是暂时还想不到别的办法。 有人可以建议对此进行任何优化吗?
【问题讨论】:
-
您可能会在Bit Twiddling Hacks 找到答案——即使您在那里没有找到答案,您也应该为该页面添加书签。
标签: c bitwise-operators bit-shift