我偶然发现了 this answer关于用于 strlen
优化的魔数(Magic Number) 0x07EFEFEFF 的使用,以下是最佳答案:
Look at the magic bits. Bits number 16, 24 and 31 are 1. 8th bit is 0.
- 8th bit represents the first byte. If the first byte is not zero, 8th bit becomes
1
at this point. Otherwise it's0
.- 16th bit represents the second byte. Same logic.
- 24th bit represents the third byte.
- 31th bit represents the fourth byte.
但是,如果我用 a = 0x100
计算 result = ((a + magic) ^ ~a) & ~magic
,我发现 result = 0x81010100
,意思是根据top answerer,a
的第二个字节等于0,这显然是错误的。
我错过了什么?
谢谢!
最佳答案
如果低位字节不为零,这些位只会告诉您字节是否为零——因此它只能告诉您第一个 0 字节,而不是第一个 0 之后的字节。
- bit8=1 表示第一个字节为零。其他字节,未知
- bit8=0 表示第一个字节非零
- bit8=0 & bit16=1 表示第二个字节为零,更高字节未知
- bit8=0 & bit16=0 表示前两个字节非零。
此外,最后一位 (bit31) 仅告诉您最后一个字节的大约 7 位(并且仅当前 3 个字节为非零时)——如果它是唯一设置的位,则最后一个字节为 0 或128(其余非零)。
关于c - 了解用于 strlen 优化的魔数(Magic Number) 0x07EFEFEFF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37902628/