Bit Mask usage in the program below from Programming Pearls

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 04:08:17

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!