How to resolve the algorithm Gray code step by step in the Common Lisp programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Gray code step by step in the Common Lisp programming language

Table of Contents

Problem Statement

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): Or: Decoding (MSB is bit 0, b is binary, g is Gray code):

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Gray code step by step in the Common Lisp programming language

Source code in the common programming language

(defun gray-encode (n)
  (logxor n (ash n -1)))

(defun gray-decode (n)
  (do ((p n (logxor p n)))
    ((zerop n) p)
    (setf n (ash n -1))))

(loop for i to 31 do
      (let* ((g (gray-encode i)) (b (gray-decode g)))
	(format t "~2d:~6b =>~6b =>~6b :~2d~%" i i g b b)))


  

You may also check:How to resolve the algorithm Untouchable numbers step by step in the C++ programming language
You may also check:How to resolve the algorithm Balanced ternary step by step in the Haskell programming language
You may also check:How to resolve the algorithm Doubly-linked list/Definition step by step in the Action! programming language
You may also check:How to resolve the algorithm Happy numbers step by step in the Ring programming language
You may also check:How to resolve the algorithm Documentation step by step in the Ring programming language