以下程序中位掩码的使用来自《Programming Pearls》

发布于 2024-12-01 21:40:22 字数 367 浏览 5 评论 0原文

我今天开始阅读“编程珍珠”,在做练习时我遇到了这个问题“你将如何实现你自己的位向量?”。当我查看解决方案时,它是这样的:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愛放△進行李 2024-12-08 21:40:22

请注意,MASK 的设置使其具有最低 SHIFT 位设置,其中 SHIFT 恰好是 BITSPERWORD 的以 2 为底的对数

因此(i & MASK)会选择i的最低5位,相当于除以32后取余(只要考虑如何取最低两位即可)例如,十进制数的位数给出除以 100 后的余数)。这给出了我们感兴趣的单词内的位数。

1 << (i & MASK)) (顺便说一下,这是一个表达式,而不是语句)现在创建一个值,其中恰好是我们'重新感兴趣已设置。使用 |= 将此值合并到内存字中将设置位向量的所需位。

Note that MASK is set such that it has the lowest SHIFT bits set, where SHIFT is exactly the base-2 logarithm of BITSPERWORD.

Therefore (i & MASK) will select the lowest 5 bits of i, 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.

梦在夏天 2024-12-08 21:40:22

0x20 是 32,所以 i & 0x1F 采用 i 模 32,因此您永远不会移位 32 位。这是一种保护措施,因为移动任何不严格小于类型大小的内容都是未定义的行为。

0x20 is 32, so i & 0x1F takes i 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文