K&R的习题2-6:没看懂input/output

K&R's exercise 2-6: Do not understand input/output

K&R 的练习 2-6:

Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

这是我对一个例子的解释input/output:

unsigned x = 315;
int p = 2;
int n = 3;
unsigned y = 9;
printf("%d\n", setbits(x, p, n, y));  // 295

这是我的推理。

位置 2 的 3 位表示 315:

0000 0001 0011 1011
             - --    

最右边的 3 位代表 9:

0000 0000 0000 1001
                ---

将 9 的最右边的 3 位设置为 315 的从 2 开始的 3 位 => 295:

0000 0001 0010 0111
             - --

我写了一些代码,然后想根据其他解决方案对其进行检查,for example。我在网上找到的两个都给出了不同的答案,313:

0000 0001 0011 1001
                --- ???

我错过了什么?

问题的描述有点含糊。你在翻译 "the n bits starting at position p" 表示位 p, p+1, ..., p+n-1。 您链接到的页面似乎说的是从位置 p 开始的 n 位 是位 p, p-1, ..., p-n+1。 所以从第 2 位开始的 3 位将是第 2、1、0 位,最右边的三位。