需要帮助来了解"getbits()"; K& R C第2章中的方法 [英] Need help understanding "getbits()" method in Chapter 2 of K&R C
问题描述
在第2章按位运算符"一节(第2.9节)中,我很难理解其中一种示例方法的工作原理.
In chapter 2, the section on bitwise operators (section 2.9), I'm having trouble understanding how one of the sample methods works.
以下是提供的方法:
unsigned int getbits(unsigned int x, int p, int n) {
return (x >> (p + 1 - n)) & ~(~0 << n);
}
这个想法是,对于给定的数字 x ,它将从位置 p 开始从右边开始返回 n 位(最右边的位是位置0).给出以下main()
方法:
The idea is that, for the given number x, it will return the n bits starting at position p, counting from the right (with the farthest right bit being position 0). Given the following main()
method:
int main(void) {
int x = 0xF994, p = 4, n = 3;
int z = getbits(x, p, n);
printf("getbits(%u (%x), %d, %d) = %u (%X)\n", x, x, p, n, z, z);
return 0;
}
输出为:
getbits(63892 (f994), 4, 3) = 5 (5)
我得到了一部分,但在大局"方面遇到了麻烦,主要是因为我不了解的小部分(没有双关语).
I get portions of this, but am having trouble with the "big picture," mostly because of the bits (no pun intended) that I don't understand.
我专门遇到问题的部分是补编:~(~0 << n)
.我想我得到了第一部分,涉及到 x ;我正在努力的就是这部分(然后是遮罩),以及如何将它们全部组合在一起以真正检索这些位. (通过代码和使用calc.exe检查我的结果,我已经验证了它的作用-谢谢上帝,它具有二进制视图!)
The part I'm specifically having issues with is the complements piece: ~(~0 << n)
. I think I get the first part, dealing with x; it's this part (and then the mask) that I'm struggling with -- and how it all comes together to actually retrieve those bits. (Which I've verified it is doing, both with code and checking my results using calc.exe -- thank God it has a binary view!)
有帮助吗?
推荐答案
在我们的示例中,我们使用16位.在这种情况下,〜0等于
Let's use 16 bits for our example. In that case, ~0 is equal to
1111111111111111
当我们将此n
位左移(在您的情况下为3)时,我们得到:
When we left-shift this n
bits (3 in your case), we get:
1111111111111000
因为左侧的1
被丢弃,而0
则在右侧被送入.然后对其进行补充,即可得到:
because the 1
s at the left are discarded and 0
s are fed in at the right. Then re-complementing it gives:
0000000000000111
因此,这是在数字的最低有效部分中获取n
1位的聪明方法.
so it's just a clever way to get n
1-bits in the least significant part of the number.
您描述的"x位"已将给定数字(f994)右移了足够远,因此,最低3位是您想要的.在此示例中,您所请求的位用."括起来.字符.
The "x bit" you describe has shifted the given number (f994) right far enough so that the least significant 3 bits are the ones you want. In this example, the bits you're requesting are surrounded by '.' characters.
ff94 11111111100.101.00 # original number
>> p+1-n [2] 0011111111100.101. # shift desired bits to right
& ~(~0 << n) [7] 0000000000000.101. # clear all the other (left) bits
在那里有你的东西. da !!
And there you have your bits. Ta da !!
这篇关于需要帮助来了解"getbits()"; K& R C第2章中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!