c - 了解用于 strlen 优化的魔数(Magic Number) 0x07EFEFEFF

标签 c assembly bit-manipulation strlen

我偶然发现了 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'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,意思是根据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/

相关文章:

c++ - 将指针作为参数传递给从属 dll 对象大小错误

c++ - 在运行时以编程方式检测 CPU 架构

c++ - 编译为 C++ 与 C 时 GCC 代码生成的巨大差异

java - java中i &=(i-1) 的含义是什么

assembly - "shift operates on bits individually"是什么意思?

c Valgrind 大小 4 的读取无效 -> 段错误

java - 在 Java 中释放对象

c++ - 位压缩结构

c - 在 C 中取证删除硬盘上的文件

c - 强制 gcc 使用系统调用