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.
 
    for r =0 to 31
        print " Decimal "; using( "###", r); " is ";
        B$ =dec2Bin$( r)
        print " binary "; B$; ". Binary "; B$;
        G$ =Bin2Gray$( dec2Bin$( r))
        print " is "; G$; " in Gray code, or ";
        B$ =Gray2Bin$( G$)
        print B$; " in pure binary."
    next r
 
    end
 
    function Bin2Gray$( bin$)   '   Given a binary number as a string, returns Gray code as a string.
        g$ =left$( bin$, 1)
        for i =2 to len( bin$)
            bitA    =val( mid$( bin$, i -1, 1))
            bitB    =val( mid$( bin$, i,    1))
            AXorB   =bitA xor bitB
            g$      =g$ +str$( AXorB)
        next i
        Bin2Gray$ =g$
    end function
 
    function Gray2Bin$( g$)     '   Given a Gray code as a string, returns equivalent binary num. 
                                '      as a string
        gl =len(   g$)
        b$ =left$( g$, 1)
        for i =2 to len( g$)
            bitA    =val( mid$( b$, i -1, 1))
            bitB    =val( mid$( g$, i,    1))
            AXorB   =bitA xor bitB
            b$      =b$ +str$( AXorB)
        next i
        Gray2Bin$ =right$( b$, gl)
    end function
 
    function dec2Bin$( num) '   Given an integer decimal, returns binary equivalent as a string
        n =num
        dec2Bin$ =""
        while ( num >0)
            dec2Bin$    =str$( num mod 2) +dec2Bin$
            num         =int( num /2)
        wend
        if ( n >255) then nBits =16 else nBits =8
        dec2Bin$ =right$( "0000000000000000" +dec2Bin$, nBits)  '   Pad to 8 bit or 16 bit
    end function
 
    function bin2Dec( b$)   '   Given a binary number as a string, returns decimal equivalent num.
        t =0
        d =len( b$)
        for k =d to 1 step -1
            t   =t +val( mid$( b$, k, 1)) *2^( d -k)
        next k
        bin2Dec =t
    end function
 