October 28, 2004

Improvement to finding a zero byte in a word

Paul Messmer sent me an improvement to my bithack for determining if a word has a zero byte.  It performs a quick pretest, which produces false positives on the rare occasions that the first byte is 0x80.  All positives are checked using the more reliable method.  Because it only takes 3 operations for the fast pretest, it runs faster.

bool mayHaveZeroByte = ((v + 0x7efefeff) ^ ~v) & 0x81010100;
if (mayHaveZeroByte) // or may just have 0x80 in the high byte
  {
  bool hasZeroByte = ~((((v & 0x7F7F7F7F) + 0x7F7F7F7F) | v) | 0x7F7F7F7F);
  }
Posted by seander at October 28, 2004 03:41 PM
Comments