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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Gray code step by step in the Nim 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 Nim programming language

Source code in the nim programming language

proc grayEncode(n: int): int =
  n xor (n shr 1)
 
proc grayDecode(n: int): int =
  result = n
  var t = n
  while t > 0:
    t = t shr 1
    result = result xor t


import strutils, strformat
 
for i in 0 .. 32:
  echo &"{i:>2} => {toBin(grayEncode(i), 6)} => {grayDecode(grayEncode(i)):>2}"


  

You may also check:How to resolve the algorithm Gray code step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Pythagorean triples step by step in the Wren programming language
You may also check:How to resolve the algorithm First-class functions step by step in the Lang programming language
You may also check:How to resolve the algorithm Split a character string based on change of character step by step in the D programming language
You may also check:How to resolve the algorithm Function frequency step by step in the REXX programming language