题目分析:
xxx...xnnnx...xxx x
yy..............ynnn y
要变成这样的效果。
我们需要对x中n位清零,把y中最右边n位其他以为的位都清零并左移到第p位处,然后进行or操作。
xxx....x000x...xxx
000... nnn....000 |
--------------------------
xxx....xnnnx...xxx
1.对x中n位清零: 这里想到与运算,x中n位与零相与n位得到0,其余位与1相与(这样可以保持其他位不变)。
~(~0<< n): 得到最低n位为1,其余各位为0的位串信息。000......111
将~(~0<< n)左移(p+1-n) 位得到 000..01110...000
然后取反得到 111...10001.111
最后与x相与可得到 xxx...x000x...xxx
2. 对y处理:
运用 ~(~0<< n): 得到最低n位为1,其余各位为0的位串信息。000......111
然后与y相与得到 000......0nnn
最后左移(p+1-n) 得到 000...nnn....000
代码如下:
/* setbits : set n bits of x at position p with bits of y */
unsigned setbits ( unsigned x, int p, int n, unsigned y)
{
return x &~(~(~0<< n) << (p + 1 -n)) | (y & ~(~0 <<n )) << (p + 1 - n)
}
}