Code Poetry
and Text Adventures

by catid posted (>30 days ago) 10:16pm Tue. Dec 13th 2016 PST
Determine which bit 0..7 to flip to generate the next Gray code value, without a table: (Haven't seen this before)

// Get the next bit to flip to produce the 8-bit Gray code at the provided index
// Precondition: index > 0 and index < 256
static int GetBitFlipForGrayCode8(int index)
{
   if (index & 1)
      return 0;

   if (index & 15)
      return (0x6764 >> (index & 14)) & 3;

   return ((0x12131210 >> (index >> 3)) & 3) + 4;
}

It's roughly 2x faster than using the x ^ (x >> 1) trick twice and using BSF instruction to identify where the bit flip happened.
last edit by catid edited (>30 days ago) 10:54pm Tue. Dec 13th 2016 PST