Gray code: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 31:
{{trans|Python: on integers}}
 
<langsyntaxhighlight lang="11l">F gray_encode(n)
R n (+) n >> 1
 
Line 45:
V gray = gray_encode(i)
V dec = gray_decode(gray)
print(‘ #2, #. => #. => #2’.format(i, bin(i).zfill(5), bin(gray).zfill(5), dec))</langsyntaxhighlight>
 
{{out}}
Line 87:
 
 
<langsyntaxhighlight lang="8080asm"> org 100h
xra a ; set A=0
loop: push psw ; print number as decimal
Line 170:
jmp 5
arrow: db ' ==> $'
nl: db 13,10,'$'</langsyntaxhighlight>
 
{{out}}
Line 210:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC ToBinaryStr(BYTE n CHAR ARRAY s)
BYTE i
 
Line 267:
PrintB2(b) PutE()
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Gray_code.png Screenshot from Atari 8-bit computer]
Line 309:
Values are implemented with 8 bits according to representation clause
of Unsigned_8 (check package Interfaces).
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Interfaces;
use Ada.Text_IO, Interfaces;
 
Line 355:
New_Line;
end loop;
end Gray;</langsyntaxhighlight>
Check compactness of assembly code generated by GNAT :http://pastebin.com/qtNjeQk9<br>
{{out}}
Line 394:
=={{header|Aime}}==
{{trans|C}}
<langsyntaxhighlight lang="aime">integer
gray_encode(integer n)
{
Line 411:
 
p;
}</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="aime">integer
main(void)
{
Line 436:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> 0: 00000 => 00000 => 00000: 0
Line 473:
=={{header|ALGOL 68}}==
In Algol 68 the BITS mode is specifically designed for manipulating machine words as a row of bits so it is natural to treat Gray encoded integers as values of MODE BITS. The standard operator BIN (INT) : BITS converts an INT value to a BITS value. The ABS (BITS) : INT operator performs the reverse conversion, though it has not been needed for this task. It is also natural in the language for simple operations on values to be implemented as operators, rather than as functions, as in the program below.
<langsyntaxhighlight lang="algol68">BEGIN
OP GRAY = (BITS b) BITS : b XOR (b SHR 1); CO Convert to Gray code CO
OP YARG = (BITS g) BITS : CO Convert from Gray code CO
Line 484:
printf (($zd, ": ", 2(2r5d, " >= "), 2r5dl$, i, BIN i, GRAY BIN i, YARG GRAY BIN i))
OD
END</langsyntaxhighlight>
{{out}}
<pre> 0: 00000 >= 00000 >= 00000
Line 523:
{{trans|C}}
Version: Hopper-BASIC.
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#proto GrayEncode(_X_)
#synon _GrayEncode *getGrayEncode
Line 555:
Wend
Return (p)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 596:
 
Generate the complete N-bit Gray sequence as a matrix:<sup>[http://ngn.github.io/apl/web/index.html#code=N%u21905%0A%28%7B%280%2C%u2375%29%u236A1%2C%u2296%u2375%7D%u2363N%29%281%200%u2374%u236C%29,run=1 run]</sup>
<langsyntaxhighlight lang="apl">N←5
({(0,⍵)⍪1,⊖⍵}⍣N)(1 0⍴⍬)</langsyntaxhighlight>
{{out}}
<pre style="overflow: auto; height: 20em;">0 0 0 0 0
Line 633:
 
Encode and decode an individual integer:<sup>[http://ngn.github.io/apl/web/index.html#code=N%u21905%0AgrayEncode%u2190%7Ba%u2260N%u2191%280%2Ca%u2190%28N%u23742%29%u22A4%u2375%29%7D%0AgrayDecode%u2190%7B2%u22A5%u2260%u233FN%20N%u2191N%282%D7N%29%u2374%u2375%2C0%2CN%u23740%7D%0A%0AgrayEncode%2019,run=1 run]</sup>
<langsyntaxhighlight lang="apl">N←5
grayEncode←{a≠N↑(0,a←(N⍴2)⊤⍵)}
grayDecode←{2⊥≠⌿N N↑N(2×N)⍴⍵,0,N⍴0}
 
grayEncode 19</langsyntaxhighlight>
{{out}}
<pre>1 1 0 1 0</pre>
Line 643:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">toGray: function [n]-> xor n shr n 1
fromGray: function [n][
p: n
Line 664:
pad to :string decoded 2
]
]</langsyntaxhighlight>
 
{{out}}
Line 702:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AHKlang="ahk">gray_encode(n){
return n ^ (n >> 1)
}
Line 724:
n:=A_Index-1, out .= n " : " BinString(n) " => " BinString(e:=gray_encode(n))
. " => " BinString(gray_decode(e)) " => " BinString(n) "`n"
MsgBox % clipboard := out</langsyntaxhighlight>
{{out}}
<pre style="overflow: auto; height: 20em;">0 : 00000 => 00000 => 00000 => 00000
Line 760:
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk"># Tested using GAWK
 
function bits2str(bits, data, mask)
Line 796:
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)))
}</langsyntaxhighlight>
{{out}}
<pre>0 => 00000 => 00000 => 00000
Line 832:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">:: Gray Code Task from Rosetta Code
:: Batch File Implementation
Line 893:
echo(%%n -^> !bin! -^> !gray! -^> !rebin!
)
exit /b 0</langsyntaxhighlight>
{{Out}}
<pre style="overflow: auto; height: 20em;"># -> bin -> enc -> dec
Line 931:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"STRINGLIB"
PRINT " Decimal Binary Gray Decoded"
Line 945:
DEF FNgraydecode(G%) : LOCAL B%
REPEAT B% EOR= G% : G% = G% >>> 1 : UNTIL G% = 0
= B%</langsyntaxhighlight>
 
=={{header|bc}}==
This language has no bitwise logic. We must repeat, with each bit, the exclusive-or calculation. This solution uses <tt>h % 2</tt> and <tt>i % 2</tt> to grab the low bits, and repeats <tt>if (h % 2 != i % 2)</tt> to check if the exclusive-or is one. Our encoding and decoding functions are identical except that <tt>h</tt> always comes from the decoded integer.
 
<langsyntaxhighlight lang="bc">scale = 0 /* to use integer division */
 
/* encode Gray code */
Line 995:
"
}
quit</langsyntaxhighlight>
 
{{out}}
Line 1,033:
=={{header|C}}==
{{trans|Tcl}}
<langsyntaxhighlight lang="c">int gray_encode(int n) {
return n ^ (n >> 1);
}
Line 1,041:
while (n >>= 1) p ^= n;
return p;
}</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="c">#include <stdio.h>
 
/* Simple bool formatter, only good on range 0..31 */
Line 1,066:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,104:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="c sharp">using System;
 
public class Gray {
Line 1,126:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,165:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <bitset>
#include <iostream>
Line 1,203:
std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n";
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,242:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
gray_encode = (n) ->
n ^ (n >> 1)
Line 1,253:
for i in [0..32]
console.log gray_decode gray_encode(i)
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun gray-encode (n)
(logxor n (ash n -1)))
 
Line 1,266:
(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)))</langsyntaxhighlight>
 
{{out}}
Line 1,306:
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE GrayCodes;
IMPORT StdLog,SYSTEM;
Line 1,358:
 
END GrayCodes.
</syntaxhighlight>
</lang>
Execute: ^QGrayCodes.Do<br/>
{{out}}
Line 1,401:
=={{header|Crystal}}==
{{trans|C}}
<langsyntaxhighlight lang="ruby">
def gray_encode(bin)
bin ^ (bin >> 1)
Line 1,414:
bin
end
</syntaxhighlight>
</lang>
Demonstration code:
<langsyntaxhighlight lang="ruby">
(0..31).each do |n|
gr = gray_encode n
Line 1,422:
printf "%2d : %05b => %05b => %05b : %2d\n", n, n, gr, bin, bin
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,460:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">uint grayEncode(in uint n) pure nothrow @nogc {
return n ^ (n >> 1);
}
Line 1,481:
assert(d == n);
}
}</langsyntaxhighlight>
{{out}}
<pre> N N2 enc dec2 dec
Line 1,523:
then the decode table is calculated and appended.
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
T[] gray(int N : 1, T)() pure nothrow {
Line 1,560:
writefln("%2d: %5b => %5b : %2d", i, i, encoded, decoded);
}
}</langsyntaxhighlight>
 
===Short Functional-Style Generator===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
string[] g(in uint n) pure nothrow {
Line 1,573:
void main() {
4.g.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>["0000", "0001", "0011", "0010", "0110", "0111", "0101", "0100", "1100", "1101", "1111", "1110", "1010", "1011", "1001", "1000"]</pre>
Line 1,579:
=={{header|Delphi}}==
{{trans|DWScript}}
<langsyntaxhighlight lang="delphi">program GrayCode;
 
{$APPTYPE CONSOLE}
Line 1,623:
Writeln(Format(' %2d %s %s %s %2d', [i, IntToBin(i, 5), IntToBin(g, 5), IntToBin(d, 5), d]));
end;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,663:
=={{header|DWScript}}==
 
<langsyntaxhighlight lang="delphi">function Encode(v : Integer) : Integer;
begin
Result := v xor (v shr 1);
Line 1,685:
PrintLn(Format(' %2d %s %s %s %2d',
[i, IntToBin(i, 5), IntToBin(g, 5), IntToBin(d, 5), d]));
end;</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Gray_code do
use Bitwise
def encode(n), do: bxor(n, bsr(n,1))
Line 1,703:
d = Gray_code.decode(g)
:io.fwrite("~2B : ~5.2.0B : ~5.2.0B : ~5.2.0B : ~2B~n", [n, n, g, d, d])
end)</langsyntaxhighlight>
output is the same as "Erlang".
 
=={{header|Erlang}}==
{{trans|Euphoria}}
<langsyntaxhighlight lang="erlang">-module(gray).
-export([encode/1, decode/1]).
 
Line 1,717:
decode(0,N) -> N;
decode(G,N) -> decode(G bsr 1, G bxor N).
</syntaxhighlight>
</lang>
 
Demonstration code:
<langsyntaxhighlight lang="erlang">-module(testgray).
 
test_encode(N) ->
Line 1,730:
test_encode(I, N) when I < N -> test_encode(I), test_encode(I+1, N).
 
main(_) -> test_encode(0,32).</langsyntaxhighlight>
 
{{out}}
Line 1,769:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function gray_encode(integer n)
return xor_bits(n,floor(n/2))
end function
Line 1,802:
j = gray_decode(j)
printf(1,"%05d\n",dcb(j))
end for</langsyntaxhighlight>
 
{{out}}
Line 1,840:
=={{header|F_Sharp|F#}}==
===The Function===
<langsyntaxhighlight lang="fsharp">
// Functıons to translate bınary to grey code and vv. Nigel Galloway: December 7th., 2018
let grayCode,invGrayCode=let fN g (n:uint8)=n^^^(n>>>g) in ((fN 1),(fN 1>>fN 2>>fN 4))
</syntaxhighlight>
</lang>
===The Task===
<langsyntaxhighlight lang="fsharp">
[0uy..31uy]|>List.iter(fun n->let g=grayCode n in printfn "%2d -> %5s (%2d) -> %2d" n (System.Convert.ToString(g,2)) g (invGrayCode g))</langsyntaxhighlight>
{{out}}
<pre>
Line 1,885:
=={{header|Factor}}==
Translation of C.
<langsyntaxhighlight lang="factor">USING: math.ranges locals ;
IN: rosetta-gray
 
Line 1,901:
 
MAIN: main
</syntaxhighlight>
</lang>
Running above code prints:
<langsyntaxhighlight lang="factor">{ -1 "-1" "0" 0 }
{ 0 "0" "0" 0 }
{ 1 "1" "1" 1 }
Line 1,936:
{ 30 "11110" "10001" 30 }
{ 31 "11111" "10000" 31 }
{ 32 "100000" "110000" 32 }</langsyntaxhighlight>
 
=={{header|Forth}}==
Line 1,942:
These functions take input parameters from the stack and return the result on the stack.
 
<langsyntaxhighlight lang="forth">: >gray ( n -- n' ) dup 2/ xor ; \ n' = n xor (n logically right shifted 1 time)
\ 2/ is Forth divide by 2, ie: shift right 1
: gray> ( n -- n )
Line 1,963:
loop
decimal ; \ revert to BASE 10
</langsyntaxhighlight>
{{out}}
<pre>
Line 2,002:
=={{header|Fortran}}==
Using [http://www.everyspec.com/MIL-STD/MIL-STD+(1700+-+1799)/download.php?spec=MIL-STD-1753.011044.PDF MIL-STD-1753] extensions in '''Fortran 77''', and formulas found at OEIS for [[oeis:A003188|direct]] and [[oeis:A006068|inverse]] Gray code :
<langsyntaxhighlight lang="fortran"> PROGRAM GRAY
IMPLICIT NONE
INTEGER IGRAY,I,J,K
Line 2,047:
10 CONTINUE
S(1:L-K)=''
END</langsyntaxhighlight>
 
<pre> 0 : 00000 => 00000 => 00000 : 0
Line 2,083:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 18-01-2017
' compile with: fbc -s console
 
Line 2,123:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre> i binary gray gra2bin
Line 2,162:
=={{header|Frink}}==
Frink has built-in functions to convert to and from binary reflected Gray code.
<langsyntaxhighlight lang="frink">
for i=0 to 31
{
Line 2,169:
println[(i->binary) + "\t" + (gray->binary) + "\t" + (back->binary)]
}
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
{{trans|Euphoria}}
Binary reflected, as described in the task. Reading down through the solutions, the Euphoria decode algorithm caught my eye as being concise and easy to read.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,196:
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,236:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def grayEncode = { i ->
i ^ (i >>> 1)
}
Line 2,245:
def h = grayDecode(code >>> 1)
return (h << 1) + ((code ^ h) & 1)
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def binary = { i, minBits = 1 ->
def remainder = i
def bin = []
Line 2,268:
it, iB[4],iB[3],iB[2],iB[1],iB[0], cB[4],cB[3],cB[2],cB[1],cB[0], decode)
println()
}</langsyntaxhighlight>
 
Results:
Line 2,309:
For zero padding, replace the %5s specifiers in the format string with %05s.
 
<langsyntaxhighlight Haskelllang="haskell">import Data.Bits
import Data.Char
import Numeric
Line 2,331:
printf "int: %2d -> bin: %5s -> gray: %5s\n" num bin gray
 
main = forM_ [0..31::Int] showGrayCode</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
 
The following works in both languages:
<langsyntaxhighlight lang="unicon">link bitint
 
procedure main()
Line 2,353:
every i := 2 to *g do b ||:= if g[i] == b[i-1] then "0" else "1"
return b
end</langsyntaxhighlight>
 
Sample run:
Line 2,376:
<code>G2B</code> is an invertible function which will translate Gray code to Binary:
 
<langsyntaxhighlight lang="j">G2B=: ~:/\&.|:</langsyntaxhighlight>
 
Thus <code>G2B inv</code> will translate binary to Gray code.
Line 2,382:
Required example:
 
<langsyntaxhighlight lang="j"> n=:i.32
G2B=: ~:/\&.|:
(,: ,.@".&.>) 'n';'#:n';'G2B inv#:n';'#.G2B G2B inv#:n'
Line 2,420:
|30|1 1 1 1 0|1 0 0 0 1 |30 |
|31|1 1 1 1 1|1 0 0 0 0 |31 |
+--+---------+----------+----------------+</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|C}}
<langsyntaxhighlight lang="java">
public class Gray {
public static long grayEncode(long n){
Line 2,446:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,485:
</pre>
Here is an example encoding function that does it in a bit-by-bit, more human way:
<langsyntaxhighlight lang="java">public static long grayEncode(long n){
long result = 0;
for(int exp = 0; n > 0; n /= 2, exp++){
Line 2,496:
}
return result;
}</langsyntaxhighlight>
This decoding function should work for gray codes of any size:
{{untested}}
<langsyntaxhighlight lang="java">public static BigInteger grayDecode(BigInteger n){
String nBits = n.toString(2);
String result = nBits.substring(0, 1);
Line 2,509:
}
return new BigInteger(result, 2);
}</langsyntaxhighlight>
 
=={{header|Javascript}}==
Line 2,515:
 
'''Module''' <code>gray-code.js</code>
<langsyntaxhighlight lang="javascript">export function encode (number) {
return number ^ (number >> 1)
}
Line 2,527:
 
return number
}</langsyntaxhighlight>
'''Test'''
<langsyntaxhighlight lang="javascript">import printf from 'printf' // Module must be installed with npm first
import * as gray from './gray-code.js'
 
Line 2,550:
decodedGrayCode
))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,591:
{{works with|Julia|0.6}}
{{trans|C}}
<langsyntaxhighlight lang="julia">grayencode(n::Integer) = n ⊻ (n >> 1)
function graydecode(n::Integer)
r = n
Line 2,598:
end
return r
end</langsyntaxhighlight>
 
Note that these functions work for any integer type, including arbitrary-precision integers (the built-in <code>BigInt</code> type).
Line 2,606:
Binary to Gray code
 
<langsyntaxhighlight Klang="k"> xor: {~x=y}
gray:{x[0],xor':x}
 
Line 2,613:
/ variant: iterative
gray2:{x[0],{:[x[y-1]=1;~x[y];x[y]]}[x]'1+!(#x)-1}</langsyntaxhighlight>
 
 
Line 2,619:
 
"Accumulated xor"
<syntaxhighlight lang K="k"> g2b:xor\</langsyntaxhighlight>
 
An alternative is to find the inverse of the gray code by tracing until fixpoint.
Here we find that 1 1 1 1 1 is the inverse of 1 0 0 0 0
<langsyntaxhighlight Klang="k"> gray\1 0 0 0 0
(1 0 0 0 0
1 1 0 0 0
Line 2,632:
1 0 1 0 1
1 1 1 1 1)
</syntaxhighlight>
</lang>
 
As a function (*| takes the last result)
<langsyntaxhighlight Klang="k"> g2b1:*|{gray x}\</langsyntaxhighlight>
 
Iterative version with "do"
<langsyntaxhighlight Klang="k"> g2b2:{c:#x;b:c#0;b[0]:x[0];i:1;do[#x;b[i]:xor[x[i];b[i-1]];i+:1];b}</langsyntaxhighlight>
 
 
Presentation
 
<langsyntaxhighlight Klang="k"> gray:{x[0],xor':x}
g2b:xor\
/ using allcomb instead of 2_vs'!32 for nicer presentation
Line 2,649:
a:(+allcomb . 5 2)
`0:,/{n:2_sv x;gg:gray x;gb:g2b gg;n2:2_sv gb;
,/$((2$n)," : ",$x," -> ",$gg," -> ",$gb," : ",(2$n2),"\n") }'a</langsyntaxhighlight>
 
{{out}}
Line 2,686:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
object Gray {
Line 2,709:
println("${Integer.toBinaryString(g)}\t${Gray.decode(g)}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,749:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
for r =0 to 31
print " Decimal "; using( "###", r); " is ";
Line 2,805:
bin2Dec =t
end function
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,845:
{{trans|Go}}
 
<langsyntaxhighlight lang="limbo">implement Gray;
 
include "sys.m"; sys: Sys;
Line 2,894:
}
return s;
}</langsyntaxhighlight>
 
{{out}}
Line 2,934:
=={{header|Lobster}}==
{{trans|C}}
<langsyntaxhighlight Lobsterlang="lobster">def grey_encode(n) -> int:
return n ^ (n >> 1)
 
Line 2,952:
number_to_string(g, 2, 5) + " ⇾ " +
number_to_string(b, 2, 5) + " : " +
number_to_string(b, 10, 2))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,991:
=={{header|Logo}}==
{{trans|Euphoria}}
<langsyntaxhighlight lang="logo">to gray_encode :number
output bitxor :number lshift :number -1
end
Line 3,003:
]
output :value
end</langsyntaxhighlight>
 
Demonstration code, including formatters:
<langsyntaxhighlight lang="logo">to format :str :width [pad (char 32)]
while [(count :str) < :width] [
make "str word :pad :str
Line 3,034:
print (sentence (format :num 2) ": (binary :num 5) ": (binary :gray 5) ":
(binary :decoded 5) ": (format :decoded 2)) ]
bye</langsyntaxhighlight>
 
{{out}}
Line 3,074:
{{trans|Euphoria}}
This code uses the [http://bitop.luajit.org/index.html Lua BitOp] module. Designed to be a module named <tt>gray.lua</tt>.
<langsyntaxhighlight lang="lua">local _M = {}
 
local bit = require('bit')
Line 3,091:
end
 
return _M</langsyntaxhighlight>
 
Demonstration code:
<langsyntaxhighlight lang="lua">local bit = require 'bit'
local gray = require 'gray'
 
Line 3,117:
to_bit_string(i,5), to_bit_string(g, 5),
to_bit_string(gd,5), gd))
end</langsyntaxhighlight>
 
{{out}}
Line 3,161:
Additions to showing the modules/functions replacement mechanism of M2000
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Code32 (&code(), &decode()){
Const d$="{0::-2} {1:-6} {2:-6} {3:-6} {4::-2}"
Line 3,191:
// pass Code32 to GrayCode in place of doit
GrayCode ; doit as Code32
</syntaxhighlight>
</lang>
{{out}}
<pre style="overflow: auto; height: 20em;">
Line 3,230:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">graycode[n_]:=BitXor[n,BitShiftRight[n]]
graydecode[n_]:=Fold[BitXor,0,FixedPointList[BitShiftRight,n]]</langsyntaxhighlight>
{{out}}
<pre>Required example:
Line 3,247:
=={{header|MATLAB}}==
 
<syntaxhighlight lang="matlab">
<lang MATLAB>
%% Gray Code Generator
% this script generates gray codes of n bits
Line 3,291:
disp(result);
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,344:
The additional <tt>gray.coerce/2</tt> predicate converts the ''representation'' underlying a <tt>gray</tt> value into an <tt>int</tt> value or vice versa (it is moded in both directions). For type safety reasons we do not wish to generally expose the underlying representation, but for some purposes, most notably I/O or storage or their ilk we have to break the type safety. The <tt>coerce/2</tt> predicate is used for this purpose.
 
<langsyntaxhighlight lang="mercury">:- module gray.
 
:- interface.
Line 3,373:
gray.coerce(gray(I), I).
 
:- end_module gray.</langsyntaxhighlight>
 
The following program tests the above code:
 
<langsyntaxhighlight lang="mercury">:- module gray_test.
 
:- interface.
Line 3,416:
io.format("%8d %8s %8s\n", [i(Number), s(NumBin), s(GrayBin)], !IO).
 
:- end_module gray_test.</langsyntaxhighlight>
 
The <tt>main/2</tt> predicate generates a list of numbers from 0 to 31 inclusive and then checks that conversion is working properly.
Line 3,476:
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">proc grayEncode(n: int): int =
n xor (n shr 1)
Line 3,484:
while t > 0:
t = t shr 1
result = result xor t</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="nim">import strutils, strformat
for i in 0 .. 32:
echo &"{i:>2} => {toBin(grayEncode(i), 6)} => {grayDecode(grayEncode(i)):>2}"</langsyntaxhighlight>
{{out}}
<pre> 0 => 000000 => 0
Line 3,527:
=={{header|NOWUT}}==
adapted from C
<langsyntaxhighlight NOWUTlang="nowut">; link with PIOxxx.OBJ
 
sectiondata
Line 3,591:
endfunc
returnex $0C ; clean off 3 parameters from the stack
</syntaxhighlight>
</lang>
{{out}}
<pre style="overflow: auto; height: 20em;">00 : 00000 => 00000 => 00000
Line 3,628:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let gray_encode b =
b lxor (b lsr 1)
 
Line 3,653:
let b = gray_decode g in
Printf.printf "%2d : %s => %s => %s : %2d\n" i (s i) (s g) (s b) b
done</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
This code may have exposed a bug in PARI 2.4.4: <code>apply(Str, 1)</code> fails.
As a workaround I used a closure: <code>apply(k->Str(k), 1)</code>.
<langsyntaxhighlight lang="parigp">toGray(n)=bitxor(n,n>>1);
fromGray(n)=my(k=1,m=n);while(m>>k,n=bitxor(n,n>>k);k+=k);n;
bin(n)=concat(apply(k->Str(k),binary(n)))
 
for(n=0,31,print(n"\t"bin(n)"\t"bin(g=toGray(n))"\t"fromGray(g)))</langsyntaxhighlight>
{{out}}
<pre>0 0 0 0
Line 3,702:
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">sub bin2gray
{
return $_[0] ^ ($_[0] >> 1);
Line 3,721:
my $gr= bin2gray($_);
printf "%d\t%b\t%b\t%b\n", $_, $_, $gr, gray2bin($gr);
}</langsyntaxhighlight>
 
=={{header|Phix}}==
{{Trans|Delphi}} (turned out to be almost the same as Euphoria)
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">gray_encode</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 3,748:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d %05b %05b %2d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,788:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
<?php
 
Line 3,817:
printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,855:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
foreach(I in 0..2**5-1)
G = gray_encode1(I),
Line 3,880:
P := P ^ N,
N := N >> 1
end. </langsyntaxhighlight>
 
{{out}}
Line 3,920:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de grayEncode (N)
(bin (x| N (>> 1 N))) )
 
Line 3,929:
(mapcar
'((C) (setq X (x| X (format C))))
(chop G) ) ) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(prinl " Binary Gray Decoded")
(for I (range 0 31)
(let G (grayEncode I)
(tab (4 9 9 9) I (bin I) G (grayDecode G)) ) )</langsyntaxhighlight>
{{out}}
<pre> Binary Gray Decoded
Line 3,971:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">(stringrange, stringsize):
Gray_code: procedure options (main); /* 15 November 2013 */
declare (bin(0:31), g(0:31), b2(0:31)) bit (5);
Line 4,001:
put skip edit (i, bin(i), g(i), b2(i)) (f(2), 3(x(1), b));
end;
end Gray_code;</langsyntaxhighlight>
<pre>
0 00000 00000 00000
Line 4,038:
 
=={{header|PowerBASIC}}==
<langsyntaxhighlight lang="powerbasic">function gray%(byval n%)
gray%=n% xor (n%\2)
end function
Line 4,055:
g%=gray%(n%)
print bin$(n%);" ";bin$(g%);" ";bin$(igray%(g%))
next</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 4,065:
{{works with|SWI Prolog}}
{{works with|YAP}}
<langsyntaxhighlight Prologlang="prolog">to_gray(N, G) :-
N0 is N >> 1,
G is N xor N0.
Line 4,074:
from_gray(S, N0),
N is G xor N0
; N is G ).</langsyntaxhighlight>
 
=== Test Code ===
Line 4,082:
{{works with|SWI Prolog}}
{{works with|YAP}}
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(apply)).
 
to_gray(N, G) :-
Line 4,113:
maplist(write_record, Numbers, Grays, Decodeds).
go :- halt(1).
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,155:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.i gray_encode(n)
ProcedureReturn n ! (n >> 1)
EndProcedure
Line 4,185:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>Number Gray Binary Decoded
Line 4,225:
===Python: on integers===
Works with python integers
<syntaxhighlight lang="text">def gray_encode(n):
return n ^ n >> 1
 
Line 4,241:
gray = gray_encode(i)
dec = gray_decode(gray)
print(f" {i:>2d}, {i:>05b} => {gray:>05b} => {dec:>2d}")</langsyntaxhighlight>
 
{{out}}
Line 4,283:
 
;First some int<>bin conversion routines:
<langsyntaxhighlight lang="python">>>> def int2bin(n):
'From positive integer to list of binary bits, msb at index 0'
if n:
Line 4,299:
for bit in bits:
i = i * 2 + bit
return i</langsyntaxhighlight>
 
;Now the bin<>gray converters.
These follow closely the methods in the animation seen here: [http://www.wisc-online.com/Objects/ViewObject.aspx?ID=IAU8307 Converting Between Gray and Binary Codes].
<langsyntaxhighlight lang="python">>>> def bin2gray(bits):
return bits[:1] + [i ^ ishift for i, ishift in zip(bits[:-1], bits[1:])]
 
Line 4,309:
b = [bits[0]]
for nextb in bits[1:]: b.append(b[-1] ^ nextb)
return b</langsyntaxhighlight>
 
;Sample output
<langsyntaxhighlight lang="python">>>> for i in range(16):
print('int:%2i -> bin:%12r -> gray:%12r -> bin:%12r -> int:%2i' %
( i,
Line 4,338:
int:14 -> bin:[1, 1, 1, 0] -> gray:[1, 0, 0, 1] -> bin:[1, 1, 1, 0] -> int:14
int:15 -> bin:[1, 1, 1, 1] -> gray:[1, 0, 0, 0] -> bin:[1, 1, 1, 1] -> int:15
>>> </langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ dup 1 >> ^ ] is encodegray ( n --> n )
[ dup
Line 4,363:
i^ encodegray dup 5 echobin
say " -> "
decodegray 5 echobin cr ]</langsyntaxhighlight>
 
{{out}}
Line 4,403:
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang r>
GrayEncode <- function(binary) {
gray <- substr(binary,1,1)
Line 4,429:
return (binary)
}
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 4,451:
(~a (to-bin(gray-encode i)) #:width 5 #:align 'right #:pad-string "0")
(~a (to-bin (gray-decode(gray-encode i))) #:width 5 #:align 'right #:pad-string "0"))))
</syntaxhighlight>
</lang>
{{out}}
<pre style="overflow: auto; height: 20em;">> (show-table)
Line 4,489:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>
<lang perl6>
sub gray_encode ( Int $n --> Int ) {
return $n +^ ( $n +> 1 );
Line 4,506:
die if $d != $n;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,549:
=={{header|REXX}}==
The leading zeroes for the binary numbers and the gray code could've easily been elided.
<langsyntaxhighlight lang="rexx">/*REXX program converts decimal number ───► binary ───► gray code ───► binary.*/
parse arg N . /*get the optional argument from the CL*/
if N=='' | N=="," then N=31 /*Not specified? Then use the default.*/
Line 4,573:
end /*g*/ /* ↑ */
/* │ */
return $ /*this is an eXclusive OR ►─────────┘ */</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 4,612:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Gray code
 
Line 4,649:
result = result + string(binary)
return result
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,689:
<tt>Integer#from_gray</tt> has recursion so it can use each bit of the answer to compute the next bit.
 
<langsyntaxhighlight lang="ruby">class Integer
# Converts a normal integer to a Gray code.
def to_gray
Line 4,713:
printf "%2d : %5b => %5b => %5b : %2d\n",
number, number, encoded, decoded, decoded
end</langsyntaxhighlight>
{{out}}
<pre style="overflow: auto; height: 20em;">
Line 4,752:
=={{header|Rust}}==
{{works with|Rust|1.1}}
<langsyntaxhighlight lang="rust">fn gray_encode(integer: u64) -> u64 {
(integer >> 1) ^ integer
}
Line 4,769:
}
 
}</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 4,775:
The <code>scanLeft</code> function takes a sequence (here, of characters) and produces a collection containing cumulative results of applying an operator going left to right.
Here the operator is exclusive-or, "^", and we can use "_" placeholders to represent the arguments to the left and right. <code>tail</code> removes the "0" we added as the initial accumulator value, and <code>mkString</code> turns the collection back into a String, that we can parse into an integer (Integer.parseInt is directly from the java.lang package).
<langsyntaxhighlight lang="scala">def encode(n: Int) = (n ^ (n >>> 1)).toBinaryString
def decode(s: String) = Integer.parseInt( s.scanLeft(0)(_ ^ _.asDigit).tail.mkString , 2)
 
Line 4,781:
for (i <- 0 to 31; g = encode(i))
println("%7d %6s %5s %7s".format(i, i.toBinaryString, g, decode(g)))
</syntaxhighlight>
</lang>
{{out}}
<pre style="overflow: auto; height: 20em;">decimal binary gray decoded
Line 4,818:
</pre>
Alternatively, more imperative style:
<langsyntaxhighlight lang="scala">def encode(n: Long) = n ^ (n >>> 1)
 
def decode(n: Long) = {
Line 4,836:
val g = encode(i)
println("%7d %6s %5s %7s".format(i, toBin(i), toBin(g), decode(g)))
}</langsyntaxhighlight>
Improved version of decode using functional style (recursion+local method).
No vars and mutations.
<langsyntaxhighlight lang="scala">def decode(n:Long)={
def calc(g:Long,bits:Long):Long=if (bits>0) calc(g^bits, bits>>1) else g
calc(0, n)
}</langsyntaxhighlight>
{{out}}
<pre style="overflow: auto; height: 20em;">decimal binary gray decoded
Line 4,887:
The type [http://seed7.sourceforge.net/libraries/bin32.htm bin32] is intended for bit operations that are not defined for [http://seed7.sourceforge.net/libraries/integer.htm integer] values.
Bin32 is used for the [http://seed7.sourceforge.net/libraries/bin32.htm#%28in_bin32%29%3E%3C%28in_bin32%29 exclusive or] ('''><''') operation.
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bin32.s7i";
 
Line 4,911:
writeln(i <& " => " <& grayEncode(i) radix 2 lpad0 6 <& " => " <& grayDecode(grayEncode(i)));
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,952:
=={{header|SenseTalk}}==
Note: Inputs and outputs as strings
<langsyntaxhighlight lang="sensetalk">
function BinaryToGray param1
set theResult to ""
Line 4,990:
return theResult
end GrayToBinary
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,034:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func bin2gray(n) {
n ^ (n >> 1)
}
Line 5,047:
var gr = bin2gray(i)
printf("%d\t%b\t%b\t%b\n", i, i, gr, gray2bin(gr))
} << ^32</langsyntaxhighlight>
{{out}}
<pre>
Line 5,085:
 
=={{header|SQL}}==
<langsyntaxhighlight lang="sql">
DECLARE @binary AS NVARCHAR(MAX) = '001010111'
DECLARE @gray AS NVARCHAR(MAX) = ''
Line 5,118:
 
SELECT @binary
</syntaxhighlight>
</lang>
 
=={{header|Standard ML}}==
 
<langsyntaxhighlight lang="sml">fun gray_encode b =
Word.xorb (b, Word.>> (b, 0w1))
 
Line 5,146:
aux (i + 0w1)
end;
aux 0w0</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">func grayEncode(_ i: Int) -> Int {
return (i >> 1) ^ i
}
Line 5,171:
 
print("\(i) (\(iStr)) => \(encode) (\(encodeStr)) => \(decode) (\(decodeStr))")
}</langsyntaxhighlight>
 
{{out}}
Line 5,209:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">namespace eval gray {
proc encode n {
expr {$n ^ $n >> 1}
Line 5,222:
return $b
}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">package require Tcl 8.6; # Just for %b format specifier
for {set i 0} {$i < 32} {incr i} {
set g [gray::encode $i]
set b [gray::decode $g]
puts [format "%2d: %05b => %05b => %05b : %2d" $i $i $g $b $b]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,268:
== {{header|TypeScript}} ==
{{trans|DWScript}}
<langsyntaxhighlight lang="javascript">// Gray code
 
function encode(v: number): number {
Line 5,295:
console.log();
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,335:
=={{header|Ursala}}==
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 5,346:
#show+
 
test = mat` * 2-$'01'***K7xSS pad0*K7 <.~&,btog,gtob+ btog>* iota32</langsyntaxhighlight>
{{out}}
<pre>
Line 5,385:
=={{header|VBScript}}==
 
<langsyntaxhighlight lang="vb">Function Encoder(ByVal n)
Encoder = n Xor (n \ 2)
End Function
Line 5,413:
decoded = Decoder(encoded)
WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5))
Next</langsyntaxhighlight>
{{Out}}
<pre style="overflow: auto; height: 20em;">Binary -> Gray Code -> Binary
Line 5,453:
'''Function Based Approach:'''
 
<syntaxhighlight lang="verilog">
<lang Verilog>
`timescale 1ns/10ps
`default_nettype wire
Line 5,500:
`default_nettype none
 
</syntaxhighlight>
</lang>
 
 
'''Module Based Approach:'''
 
<syntaxhighlight lang="verilog">
<lang Verilog>
`timescale 1ns/10ps
`default_nettype none
Line 5,549:
`default_nettype none
 
</syntaxhighlight>
</lang>
 
=={{header|VHDL}}==
Combinatorial encoder:
<langsyntaxhighlight VHDLlang="vhdl">LIBRARY ieee;
USE ieee.std_logic_1164.all;
 
Line 5,566:
begin
gray <= bin(n) & ( bin(N-1 downto 0) xor bin(N downto 1));
end architecture rtl;</langsyntaxhighlight>
 
Combinatorial decoder:
<langsyntaxhighlight VHDLlang="vhdl">LIBRARY ieee;
USE ieee.std_logic_1164.all;
 
Line 5,585:
bin(i) <= gray(i) xor bin(i+1);
end generate;
end architecture rtl;</langsyntaxhighlight>
 
=={{header|Vlang}}==
{{trans|Go}}
Binary reflected, as described in the task. Reading down through the solutions, the Euphoria decode algorithm caught my eye as being concise and easy to read.
<langsyntaxhighlight lang="go">fn enc(b int) int {
return b ^ b>>1
}
Line 5,610:
println(" ${b:2} ${b:05b} ${g:05b} ${d:05b} ${d:2}")
}
}</langsyntaxhighlight>
{{out}}
<pre>Same as Go.</pre>
Line 5,616:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
 
var toGray = Fn.new { |n| n ^ (n>>1) }
Line 5,635:
System.write(" %(Fmt.bz(5, g))")
System.print(" %(Fmt.bz(5, fromGray.call(g)))")
}</langsyntaxhighlight>
 
{{out}}
Line 5,678:
Intrinsic function <code>BIN$</code> has been used.
{{works with|Windows XBasic}}
<langsyntaxhighlight lang="xbasic">' Gray code
PROGRAM "graycode"
VERSION "0.0001"
Line 5,708:
 
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,747:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
func Gray2Bin(N); \Convert N from Gray code to binary
Line 5,782:
BinOut(Gray2Bin(G)); CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 5,821:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn grayEncode(n){ n.bitXor(n.shiftRight(1)) }
fcn grayDecode(g){ b:=g; while(g/=2){ b=b.bitXor(g) } b }</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach n in ([0..31]){
g:=grayEncode(n); b:=grayDecode(g);
println("%2d(%05.2B) --> %2d(%05.2B) --> %2d(%05.2B)".fmt(n,n,g,g,b,b));
}</langsyntaxhighlight>
{{out}}
<pre style="overflow: auto; height: 20em;">
10,327

edits