以下程序中位掩码的使用来自《Programming Pearls》
我今天开始阅读“编程珍珠”,在做练习时我遇到了这个问题“你将如何实现你自己的位向量?”。当我查看解决方案时,它是这样的:
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000
int a[1 + N/BITSPERWORD];
void set(int i) { a[i >> SHIFT] |= (1 << (i & MASK));
我对这个声明感到困惑
1 << (i & MASK)
有人可以解释一下这里发生了什么吗?
I started reading "Programming Pearls" today and while doing it's exercise I came across this question "How would you implement your own bit vector?". When I looked at the solution it was like this:
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000
int a[1 + N/BITSPERWORD];
void set(int i) { a[i >> SHIFT] |= (1 << (i & MASK));
Where I am getting confused at is this statement
1 << (i & MASK)
Could someone please explain me what's going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意,
MASK
的设置使其具有最低SHIFT
位设置,其中SHIFT
恰好是BITSPERWORD 的以 2 为底的对数
。因此
(i & MASK)
会选择i
的最低5位,相当于除以32后取余(只要考虑如何取最低两位即可)例如,十进制数的位数给出除以 100 后的余数)。这给出了我们感兴趣的单词内的位数。1 << (i & MASK))
(顺便说一下,这是一个表达式,而不是语句)现在创建一个值,其中恰好是我们'重新感兴趣已设置。使用|=
将此值合并到内存字中将设置位向量的所需位。Note that
MASK
is set such that it has the lowestSHIFT
bits set, whereSHIFT
is exactly the base-2 logarithm ofBITSPERWORD
.Therefore
(i & MASK)
will select the lowest 5 bits ofi
, which is the same as taking the remainder after dividing by 32 (just consider how taking the lowest two digits of a decimal number gives you the remainder after dividing by 100, for example). That gives the number of the bit within a word we're interested in.1 << (i & MASK))
(which is, by the way, an expression, not a statement) now creates a value where exactly the bit we're interested in is set. Merging this value into the memory word with|=
will set the desired bit of the bit vector.0x20 是 32,所以 i & 0x1F 采用
i
模 32,因此您永远不会移位 32 位。这是一种保护措施,因为移动任何不严格小于类型大小的内容都是未定义的行为。0x20 is 32, so
i & 0x1F
takesi
modulo 32, so that you never shift by 32 bits. This is a safeguard because shifting by anything that isn't strictly less than the size of the type is undefined behaviour.