了解用于 strlen 优化的幻数 0x07EFEFEFF

Understanding the magic number 0x07EFEFEFF used for strlen optimization

我偶然发现 this answer 关于用于 strlen 优化的幻数 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's 0.
  • 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,这意味着根据最佳回答者,a的第二个字节等于0 ,这显然是错误的。

我错过了什么?

谢谢!

如果低位字节不为零,这些位只会告诉您字节是否为零 - 因此它只能告诉您第一个 0 字节,而不是第一个 0 之后的字节。

  • bit8=1 表示第一个字节为零。其他字节,未知
  • bit8=0 表示第一个字节非零
  • bit8=0 & bit16=1 表示第二个字节为零,更高字节未知
  • bit8=0 & bit16=0 前两个字节非零。

此外,最后一位 (bit31) 仅告诉您最后一个字节的大约 7 位(并且仅当前 3 个字节为非零时)——如果它是唯一设置的位,则最后一个字节是0 或 128(其余非零)。