题目
编写一个函数 setbits(x, p, n, y),该函数返回对x执行下列操作后的结果值:将x中从第p位开始的n个(二进制)位设置为y中最右边n位的值,x的其余各位保持不变。
题目分析
题目没说从第p位开始是向右还是向左,假设向左。
代码实现
#include <stdio.h>
unsigned setbitstemp(unsigned x, int p, int n, unsigned y);
int main()
{
int a, b;
a = 335;
b = 46;
printf("x=%d\n", setbitstemp(a, 4, 3, b));
}
unsigned setbitstemp(unsigned x, int p, int n, unsigned y)
{
int i, j, m;
i = (x >> p) & (~0 << n);
j = (y & ~(~0 << n));
m = i | j;
x = (m << p) | (x & ~(~0 << p));
return x;
}