Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.

Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).

There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."

Encoding (MSB is bit 0, b is binary, g is Gray code):

if b[i-1] = 1
   g[i] = not b[i]
else
   g[i] = b[i]
Or:

g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):

b[0] = g[0]

for other bits:
b[i] = g[i] xor b[i-1]
Reference
 Converting Between Gray and Binary Codes. It includes step-by-step animations.
 
DECLARE @BINARY AS NVARCHAR(MAX) = '001010111' 
DECLARE @gray AS NVARCHAR(MAX) = '' 
 
--Encoder 
SET @gray = LEFT(@BINARY, 1) 
 
WHILE LEN(@BINARY) > 1 
  BEGIN 
      IF LEFT(@BINARY, 1) != SUBSTRING(@BINARY, 2, 1) 
        SET @gray = @gray + '1' 
      ELSE 
        SET @gray = @gray + '0' 
 
      SET @BINARY = RIGHT(@BINARY, LEN(@BINARY) - 1) 
  END 
 
SELECT @gray 
 
--Decoder 
SET @BINARY = LEFT(@gray, 1) 
 
WHILE LEN(@gray) > 1 
  BEGIN 
      IF RIGHT(@BINARY, 1) != SUBSTRING(@gray, 2, 1) 
        SET @BINARY = @BINARY + '1' 
      ELSE 
        SET @BINARY = @BINARY + '0' 
 
      SET @gray = RIGHT(@gray, LEN(@gray) - 1) 
  END 
 
SELECT @BINARY 
 