How to resolve the algorithm Gray code step by step in the AWK programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Gray code step by step in the AWK 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 AWK programming language
Source code in the awk programming language
# Tested using GAWK
function bits2str(bits, data, mask)
{
# Source: https://www.gnu.org/software/gawk/manual/html_node/Bitwise-Functions.html
if (bits == 0)
return "0"
mask = 1
for (; bits != 0; bits = rshift(bits, 1))
data = (and(bits, mask) ? "1" : "0") data
while ((length(data) % 8) != 0)
data = "0" data
return data
}
function gray_encode(n){
# Source: https://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code
return xor(n,rshift(n,1))
}
function gray_decode(n){
# Source: https://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code
mask = rshift(n,1)
while(mask != 0){
n = xor(n,mask)
mask = rshift(mask,1)
}
return n
}
BEGIN{
for (i=0; i < 32; i++)
printf "%-3s => %05d => %05d => %05d\n",i, bits2str(i),bits2str(gray_encode(i)), bits2str(gray_decode(gray_encode(i)))
}
You may also check:How to resolve the algorithm Terminal control/Clear the screen step by step in the Phix programming language
You may also check:How to resolve the algorithm Reduced row echelon form step by step in the Sage programming language
You may also check:How to resolve the algorithm Loops/Do-while step by step in the Nemerle programming language
You may also check:How to resolve the algorithm Classes step by step in the Elena programming language
You may also check:How to resolve the algorithm Palindrome dates step by step in the PureBasic programming language