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