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.
; link with PIOxxx.OBJ
 
        sectiondata
 
output:         db " : "
inbinary:       db "00000 => "
graybinary:     db "00000 => "
outbinary:      db "00000"
                db 13,10,0        ; carriage return and null terminator
 
        sectioncode
 
start!
        gosub initplatform
 
        beginfunc
        localvar i.d,g.d,b.d
 
        i=0
        whileless i,32
        callex g,gray_encode,i
        callex b,gray_decode,g
 
        callex ,bin2string,i,inbinary,5              ; 5 = number of binary digits
        callex ,bin2string,g,graybinary,5
        callex ,bin2string,b,outbinary,5
 
        callex ,printhex8,i                  ; display hex value
                                             ; because there is no PIO routine for decimals...
        callex ,printnt,output.a
 
        i=_+1
        wend
 
        endfunc
        end
 
gray_encode:
        beginfunc n.d
        n=_ xor (n shr 1)
        endfunc n
        returnex 4                           ; clean off 1 parameter from the stack
 
gray_decode:
        beginfunc n.d
        localvar p.d
        p=n
        whilegreater n,1
        n=_ shr 1 > p=_ xor n
        wend
        endfunc p
        returnex 4                           ; clean off 1 parameter from the stack
 
bin2string:
        beginfunc digits.d,straddr.d,value.d
 
        whilegreater digits,0
        digits=_-1
        [straddr].b=value shr digits and 1+$30        ; write an ASCII '0' or '1'
        straddr=_+1                                   ; increment the pointer
        wend
 
        endfunc
        returnex $0C                         ; clean off 3 parameters from the stack
 