Gray code: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 31:
{{trans|Python: on integers}}
<
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))</
{{out}}
Line 87:
<
xra a ; set A=0
loop: push psw ; print number as decimal
Line 170:
jmp 5
arrow: db ' ==> $'
nl: db 13,10,'$'</
{{out}}
Line 210:
=={{header|Action!}}==
<
BYTE i
Line 267:
PrintB2(b) PutE()
OD
RETURN</
{{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).
<
use Ada.Text_IO, Interfaces;
Line 355:
New_Line;
end loop;
end Gray;</
Check compactness of assembly code generated by GNAT :http://pastebin.com/qtNjeQk9<br>
{{out}}
Line 394:
=={{header|Aime}}==
{{trans|C}}
<
gray_encode(integer n)
{
Line 411:
p;
}</
Demonstration code:
<
main(void)
{
Line 436:
return 0;
}</
{{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.
<
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</
{{out}}
<pre> 0: 00000 >= 00000 >= 00000
Line 523:
{{trans|C}}
Version: Hopper-BASIC.
<syntaxhighlight lang="amazing hopper">
#proto GrayEncode(_X_)
#synon _GrayEncode *getGrayEncode
Line 555:
Wend
Return (p)
</syntaxhighlight>
{{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>
<
({(0,⍵)⍪1,⊖⍵}⍣N)(1 0⍴⍬)</
{{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>
<
grayEncode←{a≠N↑(0,a←(N⍴2)⊤⍵)}
grayDecode←{2⊥≠⌿N N↑N(2×N)⍴⍵,0,N⍴0}
grayEncode 19</
{{out}}
<pre>1 1 0 1 0</pre>
Line 643:
=={{header|Arturo}}==
<
fromGray: function [n][
p: n
Line 664:
pad to :string decoded 2
]
]</
{{out}}
Line 702:
=={{header|AutoHotkey}}==
<
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</
{{out}}
<pre style="overflow: auto; height: 20em;">0 : 00000 => 00000 => 00000 => 00000
Line 760:
=={{header|AWK}}==
<
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)))
}</
{{out}}
<pre>0 => 00000 => 00000 => 00000
Line 832:
=={{header|Batch File}}==
<
:: Batch File Implementation
Line 893:
echo(%%n -^> !bin! -^> !gray! -^> !rebin!
)
exit /b 0</
{{Out}}
<pre style="overflow: auto; height: 20em;"># -> bin -> enc -> dec
Line 931:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
PRINT " Decimal Binary Gray Decoded"
Line 945:
DEF FNgraydecode(G%) : LOCAL B%
REPEAT B% EOR= G% : G% = G% >>> 1 : UNTIL G% = 0
= B%</
=={{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.
<
/* encode Gray code */
Line 995:
"
}
quit</
{{out}}
Line 1,033:
=={{header|C}}==
{{trans|Tcl}}
<
return n ^ (n >> 1);
}
Line 1,041:
while (n >>= 1) p ^= n;
return p;
}</
Demonstration code:
<
/* Simple bool formatter, only good on range 0..31 */
Line 1,066:
}
return 0;
}</
{{out}}
<pre>
Line 1,104:
=={{header|C sharp}}==
<
public class Gray {
Line 1,126:
}
}
}</
{{out}}
<pre>
Line 1,165:
=={{header|C++}}==
<
#include <bitset>
#include <iostream>
Line 1,203:
std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n";
}
}</
{{out}}
<pre>
Line 1,242:
=={{header|CoffeeScript}}==
<
gray_encode = (n) ->
n ^ (n >> 1)
Line 1,253:
for i in [0..32]
console.log gray_decode gray_encode(i)
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(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)))</
{{out}}
Line 1,306:
=={{header|Component Pascal}}==
BlackBox Component Builder
<
MODULE GrayCodes;
IMPORT StdLog,SYSTEM;
Line 1,358:
END GrayCodes.
</syntaxhighlight>
Execute: ^QGrayCodes.Do<br/>
{{out}}
Line 1,401:
=={{header|Crystal}}==
{{trans|C}}
<
def gray_encode(bin)
bin ^ (bin >> 1)
Line 1,414:
bin
end
</syntaxhighlight>
Demonstration code:
<
(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>
{{out}}
<pre>
Line 1,460:
=={{header|D}}==
<
return n ^ (n >> 1);
}
Line 1,481:
assert(d == n);
}
}</
{{out}}
<pre> N N2 enc dec2 dec
Line 1,523:
then the decode table is calculated and appended.
Same output.
<
T[] gray(int N : 1, T)() pure nothrow {
Line 1,560:
writefln("%2d: %5b => %5b : %2d", i, i, encoded, decoded);
}
}</
===Short Functional-Style Generator===
<
string[] g(in uint n) pure nothrow {
Line 1,573:
void main() {
4.g.writeln;
}</
{{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}}
<
{$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.</
{{out}}
<pre>
Line 1,663:
=={{header|DWScript}}==
<
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;</
=={{header|Elixir}}==
{{trans|Erlang}}
<
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)</
output is the same as "Erlang".
=={{header|Erlang}}==
{{trans|Euphoria}}
<
-export([encode/1, decode/1]).
Line 1,717:
decode(0,N) -> N;
decode(G,N) -> decode(G bsr 1, G bxor N).
</syntaxhighlight>
Demonstration code:
<
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).</
{{out}}
Line 1,769:
=={{header|Euphoria}}==
<
return xor_bits(n,floor(n/2))
end function
Line 1,802:
j = gray_decode(j)
printf(1,"%05d\n",dcb(j))
end for</
{{out}}
Line 1,840:
=={{header|F_Sharp|F#}}==
===The Function===
<
// 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>
===The Task===
<
[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))</
{{out}}
<pre>
Line 1,885:
=={{header|Factor}}==
Translation of C.
<
IN: rosetta-gray
Line 1,901:
MAIN: main
</syntaxhighlight>
Running above code prints:
<
{ 0 "0" "0" 0 }
{ 1 "1" "1" 1 }
Line 1,936:
{ 30 "11110" "10001" 30 }
{ 31 "11111" "10000" 31 }
{ 32 "100000" "110000" 32 }</
=={{header|Forth}}==
Line 1,942:
These functions take input parameters from the stack and return the result on the stack.
<
\ 2/ is Forth divide by 2, ie: shift right 1
: gray> ( n -- n )
Line 1,963:
loop
decimal ; \ revert to BASE 10
</
{{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 :
<
IMPLICIT NONE
INTEGER IGRAY,I,J,K
Line 2,047:
10 CONTINUE
S(1:L-K)=''
END</
<pre> 0 : 00000 => 00000 => 00000 : 0
Line 2,083:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 2,123:
Print : Print "hit any key to end program"
Sleep
End</
{{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.
<
for i=0 to 31
{
Line 2,169:
println[(i->binary) + "\t" + (gray->binary) + "\t" + (back->binary)]
}
</syntaxhighlight>
=={{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.
<
import "fmt"
Line 2,196:
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}</
{{out}}
<pre>
Line 2,236:
=={{header|Groovy}}==
Solution:
<
i ^ (i >>> 1)
}
Line 2,245:
def h = grayDecode(code >>> 1)
return (h << 1) + ((code ^ h) & 1)
}</
Test:
<
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()
}</
Results:
Line 2,309:
For zero padding, replace the %5s specifiers in the format string with %05s.
<
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</
=={{header|Icon}} and {{header|Unicon}}==
The following works in both languages:
<
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</
Sample run:
Line 2,376:
<code>G2B</code> is an invertible function which will translate Gray code to Binary:
<
Thus <code>G2B inv</code> will translate binary to Gray code.
Line 2,382:
Required example:
<
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 |
+--+---------+----------+----------------+</
=={{header|Java}}==
{{trans|C}}
<
public class Gray {
public static long grayEncode(long n){
Line 2,446:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,485:
</pre>
Here is an example encoding function that does it in a bit-by-bit, more human way:
<
long result = 0;
for(int exp = 0; n > 0; n /= 2, exp++){
Line 2,496:
}
return result;
}</
This decoding function should work for gray codes of any size:
{{untested}}
<
String nBits = n.toString(2);
String result = nBits.substring(0, 1);
Line 2,509:
}
return new BigInteger(result, 2);
}</
=={{header|Javascript}}==
Line 2,515:
'''Module''' <code>gray-code.js</code>
<
return number ^ (number >> 1)
}
Line 2,527:
return number
}</
'''Test'''
<
import * as gray from './gray-code.js'
Line 2,550:
decodedGrayCode
))
}</
{{out}}
<pre>
Line 2,591:
{{works with|Julia|0.6}}
{{trans|C}}
<
function graydecode(n::Integer)
r = n
Line 2,598:
end
return r
end</
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
<
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}</
Line 2,619:
"Accumulated xor"
<syntaxhighlight lang
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
<
(1 0 0 0 0
1 1 0 0 0
Line 2,632:
1 0 1 0 1
1 1 1 1 1)
</syntaxhighlight>
As a function (*| takes the last result)
<
Iterative version with "do"
<
Presentation
<
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</
{{out}}
Line 2,686:
=={{header|Kotlin}}==
<
object Gray {
Line 2,709:
println("${Integer.toBinaryString(g)}\t${Gray.decode(g)}")
}
}</
{{out}}
Line 2,749:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
for r =0 to 31
print " Decimal "; using( "###", r); " is ";
Line 2,805:
bin2Dec =t
end function
</syntaxhighlight>
{{out}}
<pre>
Line 2,845:
{{trans|Go}}
<
include "sys.m"; sys: Sys;
Line 2,894:
}
return s;
}</
{{out}}
Line 2,934:
=={{header|Lobster}}==
{{trans|C}}
<
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))</
{{out}}
<pre>
Line 2,991:
=={{header|Logo}}==
{{trans|Euphoria}}
<
output bitxor :number lshift :number -1
end
Line 3,003:
]
output :value
end</
Demonstration code, including formatters:
<
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</
{{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>.
<
local bit = require('bit')
Line 3,091:
end
return _M</
Demonstration code:
<
local gray = require 'gray'
Line 3,117:
to_bit_string(i,5), to_bit_string(g, 5),
to_bit_string(gd,5), gd))
end</
{{out}}
Line 3,161:
Additions to showing the modules/functions replacement mechanism of M2000
<syntaxhighlight 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>
{{out}}
<pre style="overflow: auto; height: 20em;">
Line 3,230:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
graydecode[n_]:=Fold[BitXor,0,FixedPointList[BitShiftRight,n]]</
{{out}}
<pre>Required example:
Line 3,247:
=={{header|MATLAB}}==
<syntaxhighlight lang="matlab">
%% Gray Code Generator
% this script generates gray codes of n bits
Line 3,291:
disp(result);
end
</syntaxhighlight>
{{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.
<
:- interface.
Line 3,373:
gray.coerce(gray(I), I).
:- end_module gray.</
The following program tests the above code:
<
:- interface.
Line 3,416:
io.format("%8d %8s %8s\n", [i(Number), s(NumBin), s(GrayBin)], !IO).
:- end_module gray_test.</
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}}
<
n xor (n shr 1)
Line 3,484:
while t > 0:
t = t shr 1
result = result xor t</
Demonstration code:
<
for i in 0 .. 32:
echo &"{i:>2} => {toBin(grayEncode(i), 6)} => {grayDecode(grayEncode(i)):>2}"</
{{out}}
<pre> 0 => 000000 => 0
Line 3,527:
=={{header|NOWUT}}==
adapted from C
<
sectiondata
Line 3,591:
endfunc
returnex $0C ; clean off 3 parameters from the stack
</syntaxhighlight>
{{out}}
<pre style="overflow: auto; height: 20em;">00 : 00000 => 00000 => 00000
Line 3,628:
=={{header|OCaml}}==
<
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</
=={{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>.
<
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)))</
{{out}}
<pre>0 0 0 0
Line 3,702:
=={{header|Perl}}==
<
{
return $_[0] ^ ($_[0] >> 1);
Line 3,721:
my $gr= bin2gray($_);
printf "%d\t%b\t%b\t%b\n", $_, $_, $gr, gray2bin($gr);
}</
=={{header|Phix}}==
{{Trans|Delphi}} (turned out to be almost the same as Euphoria)
<!--<
<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>
<!--</
{{out}}
<pre>
Line 3,788:
=={{header|PHP}}==
<
<?php
Line 3,817:
printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
}
</syntaxhighlight>
{{out}}
<pre>
Line 3,855:
=={{header|Picat}}==
<
foreach(I in 0..2**5-1)
G = gray_encode1(I),
Line 3,880:
P := P ^ N,
N := N >> 1
end. </
{{out}}
Line 3,920:
=={{header|PicoLisp}}==
<
(bin (x| N (>> 1 N))) )
Line 3,929:
(mapcar
'((C) (setq X (x| X (format C))))
(chop G) ) ) ) ) )</
Test:
<
(for I (range 0 31)
(let G (grayEncode I)
(tab (4 9 9 9) I (bin I) G (grayDecode G)) ) )</
{{out}}
<pre> Binary Gray Decoded
Line 3,971:
=={{header|PL/I}}==
<
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;</
<pre>
0 00000 00000 00000
Line 4,038:
=={{header|PowerBASIC}}==
<
gray%=n% xor (n%\2)
end function
Line 4,055:
g%=gray%(n%)
print bin$(n%);" ";bin$(g%);" ";bin$(igray%(g%))
next</
=={{header|Prolog}}==
Line 4,065:
{{works with|SWI Prolog}}
{{works with|YAP}}
<
N0 is N >> 1,
G is N xor N0.
Line 4,074:
from_gray(S, N0),
N is G xor N0
; N is G ).</
=== Test Code ===
Line 4,082:
{{works with|SWI Prolog}}
{{works with|YAP}}
<
to_gray(N, G) :-
Line 4,113:
maplist(write_record, Numbers, Grays, Decodeds).
go :- halt(1).
</syntaxhighlight>
{{out}}
Line 4,155:
=={{header|PureBasic}}==
<
ProcedureReturn n ! (n >> 1)
EndProcedure
Line 4,185:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
{{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}")</
{{out}}
Line 4,283:
;First some int<>bin conversion routines:
<
'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</
;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].
<
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</
;Sample output
<
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
>>> </
=={{header|Quackery}}==
<
[ dup
Line 4,363:
i^ encodegray dup 5 echobin
say " -> "
decodegray 5 echobin cr ]</
{{out}}
Line 4,403:
=={{header|R}}==
<syntaxhighlight lang="r">
GrayEncode <- function(binary) {
gray <- substr(binary,1,1)
Line 4,429:
return (binary)
}
</syntaxhighlight>
=={{header|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>
{{out}}
<pre style="overflow: auto; height: 20em;">> (show-table)
Line 4,489:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>
sub gray_encode ( Int $n --> Int ) {
return $n +^ ( $n +> 1 );
Line 4,506:
die if $d != $n;
}
</syntaxhighlight>
{{out}}
Line 4,549:
=={{header|REXX}}==
The leading zeroes for the binary numbers and the gray code could've easily been elided.
<
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 ►─────────┘ */</
'''output''' when using the default input:
<pre>
Line 4,612:
=={{header|Ring}}==
<
# Project : Gray code
Line 4,649:
result = result + string(binary)
return result
</syntaxhighlight>
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.
<
# 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</
{{out}}
<pre style="overflow: auto; height: 20em;">
Line 4,752:
=={{header|Rust}}==
{{works with|Rust|1.1}}
<
(integer >> 1) ^ integer
}
Line 4,769:
}
}</
=={{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).
<
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>
{{out}}
<pre style="overflow: auto; height: 20em;">decimal binary gray decoded
Line 4,818:
</pre>
Alternatively, more imperative style:
<
def decode(n: Long) = {
Line 4,836:
val g = encode(i)
println("%7d %6s %5s %7s".format(i, toBin(i), toBin(g), decode(g)))
}</
Improved version of decode using functional style (recursion+local method).
No vars and mutations.
<
def calc(g:Long,bits:Long):Long=if (bits>0) calc(g^bits, bits>>1) else g
calc(0, n)
}</
{{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.
<
include "bin32.s7i";
Line 4,911:
writeln(i <& " => " <& grayEncode(i) radix 2 lpad0 6 <& " => " <& grayDecode(grayEncode(i)));
end for;
end func;</
{{out}}
Line 4,952:
=={{header|SenseTalk}}==
Note: Inputs and outputs as strings
<
function BinaryToGray param1
set theResult to ""
Line 4,990:
return theResult
end GrayToBinary
</syntaxhighlight>
{{out}}
Line 5,034:
=={{header|Sidef}}==
{{trans|Perl}}
<
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</
{{out}}
<pre>
Line 5,085:
=={{header|SQL}}==
<
DECLARE @binary AS NVARCHAR(MAX) = '001010111'
DECLARE @gray AS NVARCHAR(MAX) = ''
Line 5,118:
SELECT @binary
</syntaxhighlight>
=={{header|Standard ML}}==
<
Word.xorb (b, Word.>> (b, 0w1))
Line 5,146:
aux (i + 0w1)
end;
aux 0w0</
=={{header|Swift}}==
<
return (i >> 1) ^ i
}
Line 5,171:
print("\(i) (\(iStr)) => \(encode) (\(encodeStr)) => \(decode) (\(decodeStr))")
}</
{{out}}
Line 5,209:
=={{header|Tcl}}==
<
proc encode n {
expr {$n ^ $n >> 1}
Line 5,222:
return $b
}
}</
Demonstrating:
<
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]
}</
{{out}}
<pre>
Line 5,268:
== {{header|TypeScript}} ==
{{trans|DWScript}}
<
function encode(v: number): number {
Line 5,295:
console.log();
}
</syntaxhighlight>
{{out}}
<pre>
Line 5,335:
=={{header|Ursala}}==
<
#import nat
Line 5,346:
#show+
test = mat` * 2-$'01'***K7xSS pad0*K7 <.~&,btog,gtob+ btog>* iota32</
{{out}}
<pre>
Line 5,385:
=={{header|VBScript}}==
<
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</
{{Out}}
<pre style="overflow: auto; height: 20em;">Binary -> Gray Code -> Binary
Line 5,453:
'''Function Based Approach:'''
<syntaxhighlight lang="verilog">
`timescale 1ns/10ps
`default_nettype wire
Line 5,500:
`default_nettype none
</syntaxhighlight>
'''Module Based Approach:'''
<syntaxhighlight lang="verilog">
`timescale 1ns/10ps
`default_nettype none
Line 5,549:
`default_nettype none
</syntaxhighlight>
=={{header|VHDL}}==
Combinatorial encoder:
<
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;</
Combinatorial decoder:
<
USE ieee.std_logic_1164.all;
Line 5,585:
bin(i) <= gray(i) xor bin(i+1);
end generate;
end architecture rtl;</
=={{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.
<
return b ^ b>>1
}
Line 5,610:
println(" ${b:2} ${b:05b} ${g:05b} ${d:05b} ${d:2}")
}
}</
{{out}}
<pre>Same as Go.</pre>
Line 5,616:
=={{header|Wren}}==
{{libheader|Wren-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)))")
}</
{{out}}
Line 5,678:
Intrinsic function <code>BIN$</code> has been used.
{{works with|Windows XBasic}}
<
PROGRAM "graycode"
VERSION "0.0001"
Line 5,708:
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 5,747:
=={{header|XPL0}}==
<
func Gray2Bin(N); \Convert N from Gray code to binary
Line 5,782:
BinOut(Gray2Bin(G)); CrLf(0);
];
]</
{{out}}
Line 5,821:
=={{header|zkl}}==
<
fcn grayDecode(g){ b:=g; while(g/=2){ b=b.bitXor(g) } b }</
<
g:=grayEncode(n); b:=grayDecode(g);
println("%2d(%05.2B) --> %2d(%05.2B) --> %2d(%05.2B)".fmt(n,n,g,g,b,b));
}</
{{out}}
<pre style="overflow: auto; height: 20em;">
|