Skip to content

Gray code

editable example

Click the pencil to open this in an editor, change it, and run it in your browser. The same solution is posted on Rosetta Code.

ghul
use IO.Std.write_line
bits(n: int) -> string => System.Convert.to_string(n, 2).pad_left(5, '0')
encode(n: int) -> int => n ^ (n >>> 1)
decode(gray: int) -> int => (
let n mut = gray
for shift in 1..5 do
n = n ^ (gray >>> shift)
od
n
)
write_line("binary gray decoded")
for n in 0::31 do
let gray = encode(n)
write_line("{bits(n)} {bits(gray)} {decode(gray)}")
od