Gray code: Difference between revisions

25,676 bytes added ,  17 days ago
Added Modula-2.
No edit summary
(Added Modula-2.)
 
(15 intermediate revisions by 8 users not shown)
Line 1,159:
30 => 11110 => 10001 => 11110
31 => 11111 => 10000 => 11111</pre>
 
=={{header|BASIC}}==
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"STRINGLIB"
PRINT " Decimal Binary Gray Decoded"
FOR number% = 0 TO 31
gray% = FNgrayencode(number%)
PRINT number% " " FN_tobase(number%, 2, 5) ;
PRINT " " FN_tobase(gray%, 2, 5) FNgraydecode(gray%)
NEXT
END
DEF FNgrayencode(B%) = B% EOR (B% >>> 1)
DEF FNgraydecode(G%) : LOCAL B%
REPEAT B% EOR= G% : G% = G% >>> 1 : UNTIL G% = 0
= B%</syntaxhighlight>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' version 18-01-2017
' compile with: fbc -s console
 
Function gray2bin(g As UInteger) As UInteger
Dim As UInteger b = g
While g
g Shr= 1
b Xor= g
Wend
Return b
End Function
 
Function bin2gray(b As UInteger) As UInteger
Return b Xor (b Shr 1)
End Function
 
' ------=< MAIN >=------
 
Dim As UInteger i
Print " i binary gray gra2bin"
Print String(32,"=")
For i = 0 To 31
Print Using "## --> "; i;
print Bin(i,5); " --> ";
Print Bin(bin2gray(i),5); " --> ";
Print Bin(gray2bin(bin2gray(i)),5)
Next
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
{{out}}
<pre> i binary gray gra2bin
================================
0 --> 00000 --> 00000 --> 00000
1 --> 00001 --> 00001 --> 00001
2 --> 00010 --> 00011 --> 00010
3 --> 00011 --> 00010 --> 00011
4 --> 00100 --> 00110 --> 00100
5 --> 00101 --> 00111 --> 00101
6 --> 00110 --> 00101 --> 00110
7 --> 00111 --> 00100 --> 00111
8 --> 01000 --> 01100 --> 01000
9 --> 01001 --> 01101 --> 01001
10 --> 01010 --> 01111 --> 01010
11 --> 01011 --> 01110 --> 01011
12 --> 01100 --> 01010 --> 01100
13 --> 01101 --> 01011 --> 01101
14 --> 01110 --> 01001 --> 01110
15 --> 01111 --> 01000 --> 01111
16 --> 10000 --> 11000 --> 10000
17 --> 10001 --> 11001 --> 10001
18 --> 10010 --> 11011 --> 10010
19 --> 10011 --> 11010 --> 10011
20 --> 10100 --> 11110 --> 10100
21 --> 10101 --> 11111 --> 10101
22 --> 10110 --> 11101 --> 10110
23 --> 10111 --> 11100 --> 10111
24 --> 11000 --> 10100 --> 11000
25 --> 11001 --> 10101 --> 11001
26 --> 11010 --> 10111 --> 11010
27 --> 11011 --> 10110 --> 11011
28 --> 11100 --> 10010 --> 11100
29 --> 11101 --> 10011 --> 11101
30 --> 11110 --> 10001 --> 11110
31 --> 11111 --> 10000 --> 11111</pre>
 
==={{header|GW-BASIC}}===
{{works with|BASICA}}
<syntaxhighlight lang="basic">10 DEFINT A-Z
20 FOR I=0 TO 31
30 N=I:GOSUB 200:E=R:REM Encode
40 N=E:GOSUB 300:D=R:REM Decode
50 N=I:GOSUB 400:I$=R$:REM Binary format of input
60 N=E:GOSUB 400:E$=R$:REM Binary format of encoded value
70 N=D:GOSUB 400:D$=R$:REM Binary format of decoded value
80 PRINT USING "##: \ \ => \ \ => \ \ => ##";I;I$;E$;D$;D
90 NEXT
100 END
200 REM Gray encode
210 R = N XOR N\2
220 RETURN
300 REM Gray decode
310 R = N
320 N = N\2
330 IF N=0 THEN RETURN
340 R = R XOR N
350 GOTO 320
400 REM Binary format
410 R$ = ""
420 R$ = CHR$(48+(N AND 1))+R$
430 N = N\2
440 IF N=0 THEN RETURN ELSE 420</syntaxhighlight>
{{out}}
<pre> 0: 0 => 0 => 0 => 0
1: 1 => 1 => 1 => 1
2: 10 => 11 => 10 => 2
3: 11 => 10 => 11 => 3
4: 100 => 110 => 100 => 4
5: 101 => 111 => 101 => 5
6: 110 => 101 => 110 => 6
7: 111 => 100 => 111 => 7
8: 1000 => 1100 => 1000 => 8
9: 1001 => 1101 => 1001 => 9
10: 1010 => 1111 => 1010 => 10
11: 1011 => 1110 => 1011 => 11
12: 1100 => 1010 => 1100 => 12
13: 1101 => 1011 => 1101 => 13
14: 1110 => 1001 => 1110 => 14
15: 1111 => 1000 => 1111 => 15
16: 10000 => 11000 => 10000 => 16
17: 10001 => 11001 => 10001 => 17
18: 10010 => 11011 => 10010 => 18
19: 10011 => 11010 => 10011 => 19
20: 10100 => 11110 => 10100 => 20
21: 10101 => 11111 => 10101 => 21
22: 10110 => 11101 => 10110 => 22
23: 10111 => 11100 => 10111 => 23
24: 11000 => 10100 => 11000 => 24
25: 11001 => 10101 => 11001 => 25
26: 11010 => 10111 => 11010 => 26
27: 11011 => 10110 => 11011 => 27
28: 11100 => 10010 => 11100 => 28
29: 11101 => 10011 => 11101 => 29
30: 11110 => 10001 => 11110 => 30
31: 11111 => 10000 => 11111 => 31</pre>
 
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">
for r =0 to 31
print " Decimal "; using( "###", r); " is ";
B$ =dec2Bin$( r)
print " binary "; B$; ". Binary "; B$;
G$ =Bin2Gray$( dec2Bin$( r))
print " is "; G$; " in Gray code, or ";
B$ =Gray2Bin$( G$)
print B$; " in pure binary."
next r
end
 
function Bin2Gray$( bin$) ' Given a binary number as a string, returns Gray code as a string.
g$ =left$( bin$, 1)
for i =2 to len( bin$)
bitA =val( mid$( bin$, i -1, 1))
bitB =val( mid$( bin$, i, 1))
AXorB =bitA xor bitB
g$ =g$ +str$( AXorB)
next i
Bin2Gray$ =g$
end function
 
function Gray2Bin$( g$) ' Given a Gray code as a string, returns equivalent binary num.
' as a string
gl =len( g$)
b$ =left$( g$, 1)
for i =2 to len( g$)
bitA =val( mid$( b$, i -1, 1))
bitB =val( mid$( g$, i, 1))
AXorB =bitA xor bitB
b$ =b$ +str$( AXorB)
next i
Gray2Bin$ =right$( b$, gl)
end function
 
function dec2Bin$( num) ' Given an integer decimal, returns binary equivalent as a string
n =num
dec2Bin$ =""
while ( num >0)
dec2Bin$ =str$( num mod 2) +dec2Bin$
num =int( num /2)
wend
if ( n >255) then nBits =16 else nBits =8
dec2Bin$ =right$( "0000000000000000" +dec2Bin$, nBits) ' Pad to 8 bit or 16 bit
end function
 
function bin2Dec( b$) ' Given a binary number as a string, returns decimal equivalent num.
t =0
d =len( b$)
for k =d to 1 step -1
t =t +val( mid$( b$, k, 1)) *2^( d -k)
next k
bin2Dec =t
end function
</syntaxhighlight>
{{out}}
<pre>
Decimal 0 is binary 00000000. Binary 00000000 is 00000000 in Gray code, or 00000000 in pure binary.
Decimal 1 is binary 00000001. Binary 00000001 is 00000001 in Gray code, or 00000001 in pure binary.
Decimal 2 is binary 00000010. Binary 00000010 is 00000011 in Gray code, or 00000010 in pure binary.
Decimal 3 is binary 00000011. Binary 00000011 is 00000010 in Gray code, or 00000011 in pure binary.
Decimal 4 is binary 00000100. Binary 00000100 is 00000110 in Gray code, or 00000100 in pure binary.
Decimal 5 is binary 00000101. Binary 00000101 is 00000111 in Gray code, or 00000101 in pure binary.
Decimal 6 is binary 00000110. Binary 00000110 is 00000101 in Gray code, or 00000110 in pure binary.
Decimal 7 is binary 00000111. Binary 00000111 is 00000100 in Gray code, or 00000111 in pure binary.
Decimal 8 is binary 00001000. Binary 00001000 is 00001100 in Gray code, or 00001000 in pure binary.
Decimal 9 is binary 00001001. Binary 00001001 is 00001101 in Gray code, or 00001001 in pure binary.
Decimal 10 is binary 00001010. Binary 00001010 is 00001111 in Gray code, or 00001010 in pure binary.
Decimal 11 is binary 00001011. Binary 00001011 is 00001110 in Gray code, or 00001011 in pure binary.
Decimal 12 is binary 00001100. Binary 00001100 is 00001010 in Gray code, or 00001100 in pure binary.
Decimal 13 is binary 00001101. Binary 00001101 is 00001011 in Gray code, or 00001101 in pure binary.
Decimal 14 is binary 00001110. Binary 00001110 is 00001001 in Gray code, or 00001110 in pure binary.
Decimal 15 is binary 00001111. Binary 00001111 is 00001000 in Gray code, or 00001111 in pure binary.
Decimal 16 is binary 00010000. Binary 00010000 is 00011000 in Gray code, or 00010000 in pure binary.
Decimal 17 is binary 00010001. Binary 00010001 is 00011001 in Gray code, or 00010001 in pure binary.
Decimal 18 is binary 00010010. Binary 00010010 is 00011011 in Gray code, or 00010010 in pure binary.
Decimal 19 is binary 00010011. Binary 00010011 is 00011010 in Gray code, or 00010011 in pure binary.
Decimal 20 is binary 00010100. Binary 00010100 is 00011110 in Gray code, or 00010100 in pure binary.
Decimal 21 is binary 00010101. Binary 00010101 is 00011111 in Gray code, or 00010101 in pure binary.
Decimal 22 is binary 00010110. Binary 00010110 is 00011101 in Gray code, or 00010110 in pure binary.
Decimal 23 is binary 00010111. Binary 00010111 is 00011100 in Gray code, or 00010111 in pure binary.
Decimal 24 is binary 00011000. Binary 00011000 is 00010100 in Gray code, or 00011000 in pure binary.
Decimal 25 is binary 00011001. Binary 00011001 is 00010101 in Gray code, or 00011001 in pure binary.
Decimal 26 is binary 00011010. Binary 00011010 is 00010111 in Gray code, or 00011010 in pure binary.
Decimal 27 is binary 00011011. Binary 00011011 is 00010110 in Gray code, or 00011011 in pure binary.
Decimal 28 is binary 00011100. Binary 00011100 is 00010010 in Gray code, or 00011100 in pure binary.
Decimal 29 is binary 00011101. Binary 00011101 is 00010011 in Gray code, or 00011101 in pure binary.
Decimal 30 is binary 00011110. Binary 00011110 is 00010001 in Gray code, or 00011110 in pure binary.
Decimal 31 is binary 00011111. Binary 00011111 is 00010000 in Gray code, or 00011111 in pure binary.
</pre>
 
==={{header|PowerBASIC}}===
<syntaxhighlight lang="powerbasic">function gray%(byval n%)
gray%=n% xor (n%\2)
end function
 
function igray%(byval n%)
r%=0
while n%>0
r%=r% xor n%
shift right n%,1
wend
igray%=r%
end function
 
print " N GRAY INV"
for n%=0 to 31
g%=gray%(n%)
print bin$(n%);" ";bin$(g%);" ";bin$(igray%(g%))
next</syntaxhighlight>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">Procedure.i gray_encode(n)
ProcedureReturn n ! (n >> 1)
EndProcedure
 
Procedure.i gray_decode(g)
Protected bit = 1 << (8 * SizeOf(Integer) - 2)
Protected b = g & bit, p = b >> 1
While bit > 1
bit >> 1
b | (p ! (g & bit))
p = (b & bit) >> 1
Wend
ProcedureReturn b
EndProcedure
 
If OpenConsole()
PrintN("Number Gray Binary Decoded")
Define i, n
For i = 0 To 31
g = gray_encode(i)
Print(RSet(Str(i), 2, "0") + Space(5))
Print(RSet(Bin(g, #PB_Byte), 5, "0") + Space(2))
n = gray_decode(g)
Print(RSet(Bin(n, #PB_Byte), 5, "0") + Space(3))
PrintN(RSet(Str(n), 2, "0"))
Next
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</syntaxhighlight>
{{out}}
<pre>Number Gray Binary Decoded
00 00000 00000 00
01 00001 00001 01
02 00011 00010 02
03 00010 00011 03
04 00110 00100 04
05 00111 00101 05
06 00101 00110 06
07 00100 00111 07
08 01100 01000 08
09 01101 01001 09
10 01111 01010 10
11 01110 01011 11
12 01010 01100 12
13 01011 01101 13
14 01001 01110 14
15 01000 01111 15
16 11000 10000 16
17 11001 10001 17
18 11011 10010 18
19 11010 10011 19
20 11110 10100 20
21 11111 10101 21
22 11101 10110 22
23 11100 10111 23
24 10100 11000 24
25 10101 11001 25
26 10111 11010 26
27 10110 11011 27
28 10010 11100 28
29 10011 11101 29
30 10001 11110 30
31 10000 11111 31</pre>
 
==={{header|VBScript}}===
<syntaxhighlight lang="vb">Function Encoder(ByVal n)
Encoder = n Xor (n \ 2)
End Function
 
Function Decoder(ByVal n)
Dim g : g = 0
Do While n > 0
g = g Xor n
n = n \ 2
Loop
Decoder = g
End Function
 
' Decimal to Binary
Function Dec2bin(ByVal n, ByVal length)
Dim i, strbin : strbin = ""
For i = 1 to 5
strbin = (n Mod 2) & strbin
n = n \ 2
Next
Dec2Bin = strbin
End Function
 
WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary")
For i = 0 to 31
encoded = Encoder(i)
decoded = Decoder(encoded)
WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5))
Next</syntaxhighlight>
{{Out}}
<pre style="overflow: auto; height: 20em;">Binary -> Gray Code -> Binary
00000 -> 00000 -> 00000
00001 -> 00001 -> 00001
00010 -> 00011 -> 00010
00011 -> 00010 -> 00011
00100 -> 00110 -> 00100
00101 -> 00111 -> 00101
00110 -> 00101 -> 00110
00111 -> 00100 -> 00111
01000 -> 01100 -> 01000
01001 -> 01101 -> 01001
01010 -> 01111 -> 01010
01011 -> 01110 -> 01011
01100 -> 01010 -> 01100
01101 -> 01011 -> 01101
01110 -> 01001 -> 01110
01111 -> 01000 -> 01111
10000 -> 11000 -> 10000
10001 -> 11001 -> 10001
10010 -> 11011 -> 10010
10011 -> 11010 -> 10011
10100 -> 11110 -> 10100
10101 -> 11111 -> 10101
10110 -> 11101 -> 10110
10111 -> 11100 -> 10111
11000 -> 10100 -> 11000
11001 -> 10101 -> 11001
11010 -> 10111 -> 11010
11011 -> 10110 -> 11011
11100 -> 10010 -> 11100
11101 -> 10011 -> 11101
11110 -> 10001 -> 11110
11111 -> 10000 -> 11111</pre>
 
==={{header|XBasic}}===
{{trans|DWScript}}
Intrinsic function <code>BIN$</code> has been used.
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">' Gray code
PROGRAM "graycode"
VERSION "0.0001"
 
DECLARE FUNCTION Entry()
INTERNAL FUNCTION Encode(v&)
INTERNAL FUNCTION Decode(v&)
 
FUNCTION Entry()
PRINT "decimal binary gray decoded"
FOR i& = 0 TO 31
g& = Encode(i&)
d& = Decode(g&)
PRINT FORMAT$(" ##", i&); " "; BIN$(i&, 5); " "; BIN$(g&, 5);
PRINT " "; BIN$(d&, 5); FORMAT$(" ##", d&)
NEXT i&
END FUNCTION
 
FUNCTION Encode(v&)
END FUNCTION v& ^ (v& >> 1)
 
FUNCTION Decode(v&)
result& = 0
DO WHILE v& > 0
result& = result& ^ v&
v& = v& >> 1
LOOP
END FUNCTION result&
 
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
decimal binary gray decoded
0 00000 00000 00000 0
1 00001 00001 00001 1
2 00010 00011 00010 2
3 00011 00010 00011 3
4 00100 00110 00100 4
5 00101 00111 00101 5
6 00110 00101 00110 6
7 00111 00100 00111 7
8 01000 01100 01000 8
9 01001 01101 01001 9
10 01010 01111 01010 10
11 01011 01110 01011 11
12 01100 01010 01100 12
13 01101 01011 01101 13
14 01110 01001 01110 14
15 01111 01000 01111 15
16 10000 11000 10000 16
17 10001 11001 10001 17
18 10010 11011 10010 18
19 10011 11010 10011 19
20 10100 11110 10100 20
21 10101 11111 10101 21
22 10110 11101 10110 22
23 10111 11100 10111 23
24 11000 10100 11000 24
25 11001 10101 11001 25
26 11010 10111 11010 26
27 11011 10110 11011 27
28 11100 10010 11100 28
29 11101 10011 11101 29
30 11110 10001 11110 30
31 11111 10000 11111 31
</pre>
 
=={{header|Batch File}}==
Line 1,257 ⟶ 1,724:
30 -> 11110 -> 10001 -> 11110
31 -> 11111 -> 10000 -> 11111</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"STRINGLIB"
PRINT " Decimal Binary Gray Decoded"
FOR number% = 0 TO 31
gray% = FNgrayencode(number%)
PRINT number% " " FN_tobase(number%, 2, 5) ;
PRINT " " FN_tobase(gray%, 2, 5) FNgraydecode(gray%)
NEXT
END
DEF FNgrayencode(B%) = B% EOR (B% >>> 1)
DEF FNgraydecode(G%) : LOCAL B%
REPEAT B% EOR= G% : G% = G% >>> 1 : UNTIL G% = 0
= B%</syntaxhighlight>
 
=={{header|bc}}==
Line 1,359 ⟶ 1,808:
11110 => 10001 => 11110
11111 => 10000 => 11111</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let grayEncode(n) = n neqv (n >> 1)
 
let grayDecode(n) = grayDecodeStep(0, n)
and grayDecodeStep(r, n) =
n = 0 -> r,
grayDecodeStep(r neqv n, n >> 1)
 
let binfmt(n) =
n = 0 -> 0,
(n & 1) + 10 * binfmt(n >> 1)
 
let printRow(n) be
$( let enc = grayEncode(n)
let dec = grayDecode(enc)
writef("%I2: %I5 => %I5 => %I5 => %I2*N",
n, binfmt(n), binfmt(enc), binfmt(dec), dec)
$)
 
let start() be
for i = 0 to 31 do printRow(i)</syntaxhighlight>
{{out}}
<pre> 0: 0 => 0 => 0 => 0
1: 1 => 1 => 1 => 1
2: 10 => 11 => 10 => 2
3: 11 => 10 => 11 => 3
4: 100 => 110 => 100 => 4
5: 101 => 111 => 101 => 5
6: 110 => 101 => 110 => 6
7: 111 => 100 => 111 => 7
8: 1000 => 1100 => 1000 => 8
9: 1001 => 1101 => 1001 => 9
10: 1010 => 1111 => 1010 => 10
11: 1011 => 1110 => 1011 => 11
12: 1100 => 1010 => 1100 => 12
13: 1101 => 1011 => 1101 => 13
14: 1110 => 1001 => 1110 => 14
15: 1111 => 1000 => 1111 => 15
16: 10000 => 11000 => 10000 => 16
17: 10001 => 11001 => 10001 => 17
18: 10010 => 11011 => 10010 => 18
19: 10011 => 11010 => 10011 => 19
20: 10100 => 11110 => 10100 => 20
21: 10101 => 11111 => 10101 => 21
22: 10110 => 11101 => 10110 => 22
23: 10111 => 11100 => 10111 => 23
24: 11000 => 10100 => 11000 => 24
25: 11001 => 10101 => 11001 => 25
26: 11010 => 10111 => 11010 => 26
27: 11011 => 10110 => 11011 => 27
28: 11100 => 10010 => 11100 => 28
29: 11101 => 10011 => 11101 => 29
30: 11110 => 10001 => 11110 => 30
31: 11111 => 10000 => 11111 => 31</pre>
 
=={{header|C}}==
Line 1,727 ⟶ 2,233:
32 100000%2 110000%2
</pre>
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub gray_encode(n: uint8): (r: uint8) is
r := n ^ n >> 1;
end sub;
 
sub gray_decode(n: uint8): (r: uint8) is
r := n;
while n > 0 loop
n := n >> 1;
r := r ^ n;
end loop;
end sub;
 
sub print_binary(n: uint8) is
var buf: uint8[9];
var ptr := &buf[8];
[ptr] := 0;
loop
ptr := @prev ptr;
[ptr] := (n & 1) + '0';
n := n >> 1;
if n == 0 then break; end if;
end loop;
print(ptr);
end sub;
 
sub print_row(n: uint8) is
print_i8(n);
print(":\t");
print_binary(n);
print("\t=>\t");
var gray_code := gray_encode(n);
print_binary(gray_code);
print("\t=>\t");
var decoded := gray_decode(gray_code);
print_i8(decoded);
print_nl();
end sub;
 
var i: uint8 := 0;
while i <= 31 loop
print_row(i);
i := i + 1;
end loop;</syntaxhighlight>
{{out}}
<pre>0: 0 => 0 => 0
1: 1 => 1 => 1
2: 10 => 11 => 2
3: 11 => 10 => 3
4: 100 => 110 => 4
5: 101 => 111 => 5
6: 110 => 101 => 6
7: 111 => 100 => 7
8: 1000 => 1100 => 8
9: 1001 => 1101 => 9
10: 1010 => 1111 => 10
11: 1011 => 1110 => 11
12: 1100 => 1010 => 12
13: 1101 => 1011 => 13
14: 1110 => 1001 => 14
15: 1111 => 1000 => 15
16: 10000 => 11000 => 16
17: 10001 => 11001 => 17
18: 10010 => 11011 => 18
19: 10011 => 11010 => 19
20: 10100 => 11110 => 20
21: 10101 => 11111 => 21
22: 10110 => 11101 => 22
23: 10111 => 11100 => 23
24: 11000 => 10100 => 24
25: 11001 => 10101 => 25
26: 11010 => 10111 => 26
27: 11011 => 10110 => 27
28: 11100 => 10010 => 28
29: 11101 => 10011 => 29
30: 11110 => 10001 => 30
31: 11111 => 10000 => 31</pre>
 
=={{header|Crystal}}==
Line 1,990 ⟶ 2,576:
</pre>
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc gray_encode(word n) word:
n >< (n >> 1)
corp
 
proc gray_decode(word n) word:
word r;
r := n;
while
n := n >> 1;
n > 0
do
r := r >< n
od;
r
corp
 
proc main() void:
word i, enc, dec;
for i from 0 upto 31 do
enc := gray_encode(i);
dec := gray_decode(enc);
writeln(i:2, ": ",
i:b:5, " => ",
enc:b:5, " => ",
dec:b:5, " => ",
dec:2)
od
corp</syntaxhighlight>
{{out}}
<pre> 0: 0 => 0 => 0 => 0
1: 1 => 1 => 1 => 1
2: 10 => 11 => 10 => 2
3: 11 => 10 => 11 => 3
4: 100 => 110 => 100 => 4
5: 101 => 111 => 101 => 5
6: 110 => 101 => 110 => 6
7: 111 => 100 => 111 => 7
8: 1000 => 1100 => 1000 => 8
9: 1001 => 1101 => 1001 => 9
10: 1010 => 1111 => 1010 => 10
11: 1011 => 1110 => 1011 => 11
12: 1100 => 1010 => 1100 => 12
13: 1101 => 1011 => 1101 => 13
14: 1110 => 1001 => 1110 => 14
15: 1111 => 1000 => 1111 => 15
16: 10000 => 11000 => 10000 => 16
17: 10001 => 11001 => 10001 => 17
18: 10010 => 11011 => 10010 => 18
19: 10011 => 11010 => 10011 => 19
20: 10100 => 11110 => 10100 => 20
21: 10101 => 11111 => 10101 => 21
22: 10110 => 11101 => 10110 => 22
23: 10111 => 11100 => 10111 => 23
24: 11000 => 10100 => 11000 => 24
25: 11001 => 10101 => 11001 => 25
26: 11010 => 10111 => 11010 => 26
27: 11011 => 10110 => 11011 => 27
28: 11100 => 10010 => 11100 => 28
29: 11101 => 10011 => 11101 => 29
30: 11110 => 10001 => 11110 => 30
31: 11111 => 10000 => 11111 => 31</pre>
=={{header|DWScript}}==
 
Line 2,015 ⟶ 2,663:
[i, IntToBin(i, 5), IntToBin(g, 5), IntToBin(d, 5), d]));
end;</syntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func$ bin n .
for i to 5
r$ = n mod 2 & r$
n = n div 2
.
return r$
.
func gray_encode b .
return bitxor b bitshift b -1
.
func gray_decode g .
b = g
while g > 0
g = bitshift g -1
b = bitxor b g
.
return b
.
for n = 0 to 31
g = gray_encode n
b = gray_decode g
print bin n & " -> " & bin g & " -> " & bin b
.
</syntaxhighlight>
{{out}}
<pre>
00000 -> 00000 -> 00000
00001 -> 00001 -> 00001
00010 -> 00011 -> 00010
00011 -> 00010 -> 00011
00100 -> 00110 -> 00100
00101 -> 00111 -> 00101
00110 -> 00101 -> 00110
00111 -> 00100 -> 00111
01000 -> 01100 -> 01000
01001 -> 01101 -> 01001
01010 -> 01111 -> 01010
01011 -> 01110 -> 01011
01100 -> 01010 -> 01100
01101 -> 01011 -> 01101
01110 -> 01001 -> 01110
01111 -> 01000 -> 01111
10000 -> 11000 -> 10000
10001 -> 11001 -> 10001
10010 -> 11011 -> 10010
10011 -> 11010 -> 10011
10100 -> 11110 -> 10100
10101 -> 11111 -> 10101
10110 -> 11101 -> 10110
10111 -> 11100 -> 10111
11000 -> 10100 -> 11000
11001 -> 10101 -> 11001
11010 -> 10111 -> 11010
11011 -> 10110 -> 11011
11100 -> 10010 -> 11100
11101 -> 10011 -> 11101
11110 -> 10001 -> 11110
11111 -> 10000 -> 11111
</pre>
 
=={{header|EDSAC order code}}==
The only logical operation on EDSAC was AND, or "collate" as it was called, but it's possible to calculate XOR from AND together with arithmetical operations. For converting Gray code to binary on EDSAC, I couldn't think up any shorter method than the one below.
<syntaxhighlight lang="edsac">
[Gray code task for Rosetta Code.
EDSAC program, Initial Orders 2.]
 
[Library subroutine M3. Prints header at load time,
then M3 and header are overwritten.]
PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
*BINARY!!GRAY!!!!ROUND!TRIP@&
..PK [after header, blank tape and PK (WWG, 1951, p. 91)]
 
T64K [load at location 64 (arbitrary choice)]
GK [set @ (theta) parameter]
[Subroutine to print 5-bit number in binary.
Input: 1F = number (preserved) in low 5 bits.
Workspace: 0F, 4F.]
[0] A3F T17@ [plant return link as usual]
H19@ [mult reg := mask to remove top 4 bits]
A1F [acc := code in low 5 bits]
L32F [shift 7 left]
TF [store in workspace]
S18@ [initialize negative count of digits]
[7] T4F [update negative count]
AF LD TF [shift workspace 1 left]
CF [remove top 4 bits]
TF [store result]
OF [print character '0' or '1' in top 5 bits]
A4F A2F G7@ [inc count, loop if not yet 0]
[17] ZF [{planted} jump back to caller]
[18] P5F [addres field = number of bits]
[19] Q2047D [00001111111111111 binary]
 
[Subroutine to convert binary code to Gray code.
Input: 1F = binary code (preserved).
Output: 0F = Gray code.]
[20] A3F T33@ [plant return link as usual]
A1F RD TF [0F := binary shifted 1 right]
[One way to get p XOR q on EDSAC: Let r = p AND q.
Then p XOR q = (p - r) + (q - r) = -(2r - p - q).]
HF [mult reg := 0F]
C1F [acc := 0F AND 1F]
LD [times 2]
SF S1F [subtract 0F and 1F]
TF SF TF [return result negated]
[33] ZF [{planted} jump back to caller]
 
[Subroutine to convert 5-digit Gray code to binary.
Uses a chain of XORs.
If bits in Gray code are ghijk then bits in binary are
g, g.h, g.h.i, g.h.i.j, g.h.i.j.k where dot means XOR.
Input: 1F = Gray code (preserved).
Output: 0F = binary code.
Workspace: 4F, 5F.]
[34] A3F T55@ [plant return link as usual]
A1F UF [initialize result to Gray code]
T5F [5F = shifted Gray code, shift = 0 initialiy]
S56@ [initialize negative count]
[40] T4F [update negative count]
HF [mult reg := partial result]
A5F RD T5F [shift Gray code 1 right]
[Form 5F XOR 0F as in the previous subroutine]
C5F LD SF S5F TF SF
TF [update partial result]
A4F A2F G40@ [inc count, loop back if not yet 0]
[55] ZF [{planted} jump back to caller]
[56] P4F [address field = 1 less than number of bits]
 
[Main routine]
[Variable]
[57] PF [binary code is in low 5 bits]
[Constants]
[58] P16F [exclusive maximum code, 100000 binary]
[59] PD [17-bit 1]
[60] #F [teleprinter figures mode]
[61] !F [space]
[62] @F [carriage return]
[63] &F [line feed]
[Enter with acc = 0]
[64] O60@ [set teleprinter to figures]
S58@ [to make acc = 0 after next instruction]
[66] A58@ [loop: restore acc after test below]
U57@ T1F [save binary code, and pass it to print soubroutine]
[69] A69@ G@ [print binary code]
O61@ O61@ O61@ [print 3 spaces]
[74] A74@ G20@ [convert binary (still in 1F) to Gray]
AF T1F [pass Gray code to print subroutine]
[78] A78@ G@ [print Gray code]
O61@ O61@ O61@ [print 3 spaces]
[83] A83@ G34@ [convert Gray (still in 1F) back to binary]
AF T1F [pass binary code to print subroutine]
[87] A87@ G@ [print binary]
O62@ O63@ [print CR, LF]
A57@ A59@ [inc binary]
S58@ [test for all done]
G66@ [loop back if not]
O60@ [dummy character to flush teleprinter buffer]
ZF [stop]
E64Z [define entry point]
PF [acc = 0 on entry]
[end]
</syntaxhighlight>
{{out}}
<pre>
BINARY GRAY ROUND TRIP
00000 00000 00000
00001 00001 00001
00010 00011 00010
00011 00010 00011
00100 00110 00100
00101 00111 00101
00110 00101 00110
00111 00100 00111
01000 01100 01000
01001 01101 01001
01010 01111 01010
01011 01110 01011
01100 01010 01100
01101 01011 01101
01110 01001 01110
01111 01000 01111
10000 11000 10000
10001 11001 10001
10010 11011 10010
10011 11010 10011
10100 11110 10100
10101 11111 10101
10110 11101 10110
10111 11100 10111
11000 10100 11000
11001 10101 11001
11010 10111 11010
11011 10110 11011
11100 10010 11100
11101 10011 11101
11110 10001 11110
11111 10000 11111
</pre>
 
=={{header|Elixir}}==
Line 2,410 ⟶ 3,259:
30 : 11110 => 10001 => 11110 : 30
31 : 11111 => 10000 => 11111 : 31</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' version 18-01-2017
' compile with: fbc -s console
 
Function gray2bin(g As UInteger) As UInteger
 
Dim As UInteger b = g
 
While g
g Shr= 1
b Xor= g
Wend
 
Return b
 
End Function
 
Function bin2gray(b As UInteger) As UInteger
 
Return b Xor (b Shr 1)
 
End Function
 
' ------=< MAIN >=------
 
Dim As UInteger i
 
Print " i binary gray gra2bin"
Print String(32,"=")
 
For i = 0 To 31
Print Using "## --> "; i;
print Bin(i,5); " --> ";
Print Bin(bin2gray(i),5); " --> ";
Print Bin(gray2bin(bin2gray(i)),5)
Next
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
{{out}}
<pre> i binary gray gra2bin
================================
0 --> 00000 --> 00000 --> 00000
1 --> 00001 --> 00001 --> 00001
2 --> 00010 --> 00011 --> 00010
3 --> 00011 --> 00010 --> 00011
4 --> 00100 --> 00110 --> 00100
5 --> 00101 --> 00111 --> 00101
6 --> 00110 --> 00101 --> 00110
7 --> 00111 --> 00100 --> 00111
8 --> 01000 --> 01100 --> 01000
9 --> 01001 --> 01101 --> 01001
10 --> 01010 --> 01111 --> 01010
11 --> 01011 --> 01110 --> 01011
12 --> 01100 --> 01010 --> 01100
13 --> 01101 --> 01011 --> 01101
14 --> 01110 --> 01001 --> 01110
15 --> 01111 --> 01000 --> 01111
16 --> 10000 --> 11000 --> 10000
17 --> 10001 --> 11001 --> 10001
18 --> 10010 --> 11011 --> 10010
19 --> 10011 --> 11010 --> 10011
20 --> 10100 --> 11110 --> 10100
21 --> 10101 --> 11111 --> 10101
22 --> 10110 --> 11101 --> 10110
23 --> 10111 --> 11100 --> 10111
24 --> 11000 --> 10100 --> 11000
25 --> 11001 --> 10101 --> 11001
26 --> 11010 --> 10111 --> 11010
27 --> 11011 --> 10110 --> 11011
28 --> 11100 --> 10010 --> 11100
29 --> 11101 --> 10011 --> 11101
30 --> 11110 --> 10001 --> 11110
31 --> 11111 --> 10000 --> 11111</pre>
 
=={{header|Frink}}==
Line 2,754 ⟶ 3,525:
{{trans|C}}
<syntaxhighlight lang="java">
 
public class Gray {
import java.math.BigInteger;
 
public class GrayCode {
public static long grayEncode(long n){
return n ^ ( n >>> 1 );
}
public static long grayDecode(long n) {
long p = n;
while ( ( n >>>= 1 ) != 0 ) {
p ^= n;
}
return p;
}
public static BigInteger grayEncode(BigInteger n) {
return n.xor(n.shiftRight(1));
}
public static BigInteger grayDecode(BigInteger n) {
BigInteger p = n;
while ( ( n = n.shiftRight(1) ).signum() != 0 ) {
p = p.xor(n);
}
return p;
}
/**
* An alternative version of grayDecode,
* less efficient, but demonstrates the principal of gray decoding.
*/
public static BigInteger grayDecode2(BigInteger n) {
String nBits = n.toString(2);
String result = nBits.substring(0, 1);
for ( int i = 1; i < nBits.length(); i++ ) {
// bin[i] = gray[i] ^ bin[i-1]
// XOR using characters
result += nBits.charAt(i) != result.charAt(i - 1) ? "1" : "0";
}
return new BigInteger(result, 2);
}
/**
* An alternative version of grayEncode,
* less efficient, but demonstrates the principal of gray encoding.
*/
public static long grayEncode2(long n) {
long result = 0;
for ( int exp = 0; n > 0; n >>= 1, exp++ ) {
long nextHighestBit = ( n >> 1 ) & 1;
if ( nextHighestBit == 1 ) {
result += ( ( n & 1 ) == 0 ) ? ( 1 << exp ) : 0; // flip this bit
} else {
result += ( n & 1 ) * ( 1 << exp ); // don't flip this bit
}
}
return result;
}
public static void main(String[] args){
System.out.println("i\tBinary\tGray\tGray2\tDecoded");
System.out.println("=======================================");
for(int i = -1; i < 32;i++){
for ( int i = 0; i < 32; i++ ) {
System.out.print(i +"\t");
System.out.print(i + "\t");
System.out.print(Integer.toBinaryString(i) + "\t");
System.out.print(Long.toBinaryString(grayEncode(i)) + "\t");
System.out.print(Long.toBinaryString(grayEncode2(i)) + "\t");
System.out.println(grayDecode(grayEncode(i)));
}
System.out.println();
final BigInteger base = BigInteger.TEN.pow(25).add( new BigInteger("12345678901234567890") );
for ( int i = 0; i < 5; i++ ) {
BigInteger test = base.add(BigInteger.valueOf(i));
System.out.println("test decimal = " + test);
System.out.println("gray code decimal = " + grayEncode(test));
System.out.println("gray code binary = " + grayEncode(test).toString(2));
System.out.println("decoded decimal = " + grayDecode(grayEncode(test)));
System.out.println("decoded2 decimal = " + grayDecode2(grayEncode(test)));
System.out.println();
}
}
}
</syntaxhighlight>
{{ out }}
<pre>
i Binary Gray Gray2 Decoded
=======================================
-1 11111111111111111111111111111111 1000000000000000000000000000000000000000000000000000000000000000 -1
0 0 0 0 0
1 1 1 1 1
2 10 11 11 2
3 11 10 10 3
4 100 110 110 4
5 101 111 111 5
6 110 101 101 6
7 111 100 100 7
8 1000 1100 1100 8
9 1001 1101 1101 9
10 1010 1111 1111 10
11 1011 1110 1110 11
12 1100 1010 1010 12
13 1101 1011 1011 13
14 1110 1001 1001 14
15 1111 1000 1000 15
16 10000 11000 11000 16
17 10001 11001 11001 17
18 10010 11011 11011 18
19 10011 11010 11010 19
20 10100 11110 11110 20
21 10101 11111 11111 21
22 10110 11101 11101 22
23 10111 11100 11100 23
24 11000 10100 10100 24
25 11001 10101 10101 25
26 11010 10111 10111 26
27 11011 10110 10110 27
28 11100 10010 10010 28
29 11101 10011 10011 29
30 11110 10001 10001 30
31 11111 10000 10000 31
 
test decimal = 10000012345678901234567890
gray code decimal = 14995268463904422838177723
gray code binary = 110001100111010111110010000111011100111111111011111110101111100100001000111110111011
decoded decimal = 10000012345678901234567890
decoded2 decimal = 10000012345678901234567890
 
test decimal = 10000012345678901234567891
gray code decimal = 14995268463904422838177722
gray code binary = 110001100111010111110010000111011100111111111011111110101111100100001000111110111010
decoded decimal = 10000012345678901234567891
decoded2 decimal = 10000012345678901234567891
 
test decimal = 10000012345678901234567892
gray code decimal = 14995268463904422838177726
gray code binary = 110001100111010111110010000111011100111111111011111110101111100100001000111110111110
decoded decimal = 10000012345678901234567892
decoded2 decimal = 10000012345678901234567892
 
test decimal = 10000012345678901234567893
gray code decimal = 14995268463904422838177727
gray code binary = 110001100111010111110010000111011100111111111011111110101111100100001000111110111111
decoded decimal = 10000012345678901234567893
decoded2 decimal = 10000012345678901234567893
 
test decimal = 10000012345678901234567894
gray code decimal = 14995268463904422838177725
gray code binary = 110001100111010111110010000111011100111111111011111110101111100100001000111110111101
decoded decimal = 10000012345678901234567894
decoded2 decimal = 10000012345678901234567894
</pre>
Here is an example encoding function that does it in a bit-by-bit, more human way:
<syntaxhighlight lang="java">public static long grayEncode(long n){
long result = 0;
for(int exp = 0; n > 0; n /= 2, exp++){
long nextHighestBit = (n >> 1) & 1;
if(nextHighestBit == 1){
result += ((n & 1) == 0) ? (1 << exp) : 0; //flip the bit
}else{
result += (n & 1) * (1 << exp); //"n & 1" is "this bit", don't flip it
}
}
return result;
}</syntaxhighlight>
This decoding function should work for gray codes of any size:
{{untested}}
<syntaxhighlight lang="java">public static BigInteger grayDecode(BigInteger n){
String nBits = n.toString(2);
String result = nBits.substring(0, 1);
for(int i = 1; i < nBits.length(); i++){
//bin[i] = gray[i] ^ bin[i-1]
 
//XOR with characters
result += nBits.charAt(i) != result.charAt(i - 1) ? "1" : "0";
}
return new BigInteger(result, 2);
}</syntaxhighlight>
 
=={{header|Javascript}}==
Line 2,915 ⟶ 3,755:
30 11110 10001 30
31 11111 10000 31
</pre>
 
=={{header|jq}}==
{{works with|jq}}
 
'''Works with gojq, the Go implementation of jq'''
 
'''Works with jaq, the Rust implementation of jq'''
 
The following is slightly more verbose than it need be but for the
sake of jaq.
<syntaxhighlight lang="jq">
def encode:
def flip: if . == 1 then 0 else 1 end;
. as $b
| reduce range(1; length) as $i ($b;
if $b[$i-1] == 1 then .[$i] |= flip
else .
end ) ;
 
def decode:
def xor($a;$b): ($a + $b) % 2;
. as $g
| reduce range(1; length) as $i (.[:1];
.[$i] = xor($g[$i]; .[$i-1]) ) ;
 
 
# input: a non-negative integer
# output: a binary array, least-significant bit first
def to_binary:
if . == 0 then [0]
else [recurse( if . == 0 then empty else ./2 | floor end ) % 2]
| .[:-1] # remove the uninteresting 0
end ;
 
def lpad($len; $fill):
tostring
| ($len - length) as $l
| if $l <= 0 then .
else ($fill * $l)[:$l] + .
end;
 
def pp: map(tostring) | join("") | lpad(5; "0");
 
### The task
"decimal binary gray roundtrip",
(range(0; 32) as $i
| ($i | to_binary | reverse) as $b
| ($b|encode) as $g
| " \($i|lpad(2;" ")) \($b|pp) \($g|pp) \($g|decode == $b)" )
</syntaxhighlight>
{{output}}
<pre>
decimal binary gray roundtrip
0 00000 00000 true
1 00001 00001 true
2 00010 00011 true
3 00011 00010 true
4 00100 00110 true
5 00101 00111 true
6 00110 00101 true
7 00111 00100 true
8 01000 01100 true
9 01001 01101 true
10 01010 01111 true
11 01011 01110 true
12 01100 01010 true
13 01101 01011 true
14 01110 01001 true
15 01111 01000 true
16 10000 11000 true
17 10001 11001 true
18 10010 11011 true
19 10011 11010 true
20 10100 11110 true
21 10101 11111 true
22 10110 11101 true
23 10111 11100 true
24 11000 10100 true
25 11001 10101 true
26 11010 10111 true
27 11011 10110 true
28 11100 10010 true
29 11101 10011 true
30 11110 10001 true
31 11111 10000 true
</pre>
 
Line 3,075 ⟶ 4,001:
30 11110 10001 30
31 11111 10000 31
</pre>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
for r =0 to 31
print " Decimal "; using( "###", r); " is ";
B$ =dec2Bin$( r)
print " binary "; B$; ". Binary "; B$;
G$ =Bin2Gray$( dec2Bin$( r))
print " is "; G$; " in Gray code, or ";
B$ =Gray2Bin$( G$)
print B$; " in pure binary."
next r
 
end
 
function Bin2Gray$( bin$) ' Given a binary number as a string, returns Gray code as a string.
g$ =left$( bin$, 1)
for i =2 to len( bin$)
bitA =val( mid$( bin$, i -1, 1))
bitB =val( mid$( bin$, i, 1))
AXorB =bitA xor bitB
g$ =g$ +str$( AXorB)
next i
Bin2Gray$ =g$
end function
 
function Gray2Bin$( g$) ' Given a Gray code as a string, returns equivalent binary num.
' as a string
gl =len( g$)
b$ =left$( g$, 1)
for i =2 to len( g$)
bitA =val( mid$( b$, i -1, 1))
bitB =val( mid$( g$, i, 1))
AXorB =bitA xor bitB
b$ =b$ +str$( AXorB)
next i
Gray2Bin$ =right$( b$, gl)
end function
 
function dec2Bin$( num) ' Given an integer decimal, returns binary equivalent as a string
n =num
dec2Bin$ =""
while ( num >0)
dec2Bin$ =str$( num mod 2) +dec2Bin$
num =int( num /2)
wend
if ( n >255) then nBits =16 else nBits =8
dec2Bin$ =right$( "0000000000000000" +dec2Bin$, nBits) ' Pad to 8 bit or 16 bit
end function
 
function bin2Dec( b$) ' Given a binary number as a string, returns decimal equivalent num.
t =0
d =len( b$)
for k =d to 1 step -1
t =t +val( mid$( b$, k, 1)) *2^( d -k)
next k
bin2Dec =t
end function
</syntaxhighlight>
{{out}}
<pre>
Decimal 0 is binary 00000000. Binary 00000000 is 00000000 in Gray code, or 00000000 in pure binary.
Decimal 1 is binary 00000001. Binary 00000001 is 00000001 in Gray code, or 00000001 in pure binary.
Decimal 2 is binary 00000010. Binary 00000010 is 00000011 in Gray code, or 00000010 in pure binary.
Decimal 3 is binary 00000011. Binary 00000011 is 00000010 in Gray code, or 00000011 in pure binary.
Decimal 4 is binary 00000100. Binary 00000100 is 00000110 in Gray code, or 00000100 in pure binary.
Decimal 5 is binary 00000101. Binary 00000101 is 00000111 in Gray code, or 00000101 in pure binary.
Decimal 6 is binary 00000110. Binary 00000110 is 00000101 in Gray code, or 00000110 in pure binary.
Decimal 7 is binary 00000111. Binary 00000111 is 00000100 in Gray code, or 00000111 in pure binary.
Decimal 8 is binary 00001000. Binary 00001000 is 00001100 in Gray code, or 00001000 in pure binary.
Decimal 9 is binary 00001001. Binary 00001001 is 00001101 in Gray code, or 00001001 in pure binary.
Decimal 10 is binary 00001010. Binary 00001010 is 00001111 in Gray code, or 00001010 in pure binary.
Decimal 11 is binary 00001011. Binary 00001011 is 00001110 in Gray code, or 00001011 in pure binary.
Decimal 12 is binary 00001100. Binary 00001100 is 00001010 in Gray code, or 00001100 in pure binary.
Decimal 13 is binary 00001101. Binary 00001101 is 00001011 in Gray code, or 00001101 in pure binary.
Decimal 14 is binary 00001110. Binary 00001110 is 00001001 in Gray code, or 00001110 in pure binary.
Decimal 15 is binary 00001111. Binary 00001111 is 00001000 in Gray code, or 00001111 in pure binary.
Decimal 16 is binary 00010000. Binary 00010000 is 00011000 in Gray code, or 00010000 in pure binary.
Decimal 17 is binary 00010001. Binary 00010001 is 00011001 in Gray code, or 00010001 in pure binary.
Decimal 18 is binary 00010010. Binary 00010010 is 00011011 in Gray code, or 00010010 in pure binary.
Decimal 19 is binary 00010011. Binary 00010011 is 00011010 in Gray code, or 00010011 in pure binary.
Decimal 20 is binary 00010100. Binary 00010100 is 00011110 in Gray code, or 00010100 in pure binary.
Decimal 21 is binary 00010101. Binary 00010101 is 00011111 in Gray code, or 00010101 in pure binary.
Decimal 22 is binary 00010110. Binary 00010110 is 00011101 in Gray code, or 00010110 in pure binary.
Decimal 23 is binary 00010111. Binary 00010111 is 00011100 in Gray code, or 00010111 in pure binary.
Decimal 24 is binary 00011000. Binary 00011000 is 00010100 in Gray code, or 00011000 in pure binary.
Decimal 25 is binary 00011001. Binary 00011001 is 00010101 in Gray code, or 00011001 in pure binary.
Decimal 26 is binary 00011010. Binary 00011010 is 00010111 in Gray code, or 00011010 in pure binary.
Decimal 27 is binary 00011011. Binary 00011011 is 00010110 in Gray code, or 00011011 in pure binary.
Decimal 28 is binary 00011100. Binary 00011100 is 00010010 in Gray code, or 00011100 in pure binary.
Decimal 29 is binary 00011101. Binary 00011101 is 00010011 in Gray code, or 00011101 in pure binary.
Decimal 30 is binary 00011110. Binary 00011110 is 00010001 in Gray code, or 00011110 in pure binary.
Decimal 31 is binary 00011111. Binary 00011111 is 00010000 in Gray code, or 00011111 in pure binary.
</pre>
 
=={{header|Limbo}}==
{{trans|Go}}
 
<syntaxhighlight lang="limbo">implement Gray;
 
Line 3,802 ⟶ 4,633:
30 11110 10001
31 11111 10000</tt>
 
=={{header|Modula-2}}==
{{trans|DWScript|<code>CARDINAL</code> (unsigned integer) used instead of integer.}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<syntaxhighlight lang="modula2">
MODULE GrayCode;
 
FROM STextIO IMPORT
WriteString, WriteLn;
FROM SWholeIO IMPORT
WriteInt;
FROM Conversions IMPORT
LongBaseToStr;
FROM FormatString IMPORT
FormatString; (* for justifying *)
 
VAR
I, G, D: CARDINAL;
Ok: BOOLEAN;
BinS, OutBinS: ARRAY[0 .. 5] OF CHAR;
 
PROCEDURE Encode(V: CARDINAL): CARDINAL;
BEGIN
RETURN V BXOR (V SHR 1)
END Encode;
 
PROCEDURE Decode(V: CARDINAL): CARDINAL;
VAR
Result: CARDINAL;
BEGIN
Result := 0;
WHILE V > 0 DO
Result := Result BXOR V;
V := V SHR 1
END;
RETURN Result
END Decode;
 
BEGIN
WriteString("decimal binary gray decoded");
WriteLn;
FOR I := 0 TO 31 DO
G := Encode(I);
D := Decode(G);
WriteInt(I, 4);
WriteString(" ");
Ok := LongBaseToStr(I, 2, BinS);
Ok := FormatString("%'05s", OutBinS, BinS);
(* Padded with 0; width: 5; type: string *)
WriteString(OutBinS);
WriteString(" ");
Ok := LongBaseToStr(G, 2, BinS);
Ok := FormatString("%'05s", OutBinS, BinS);
WriteString(OutBinS);
WriteString(" ");
Ok := LongBaseToStr(D, 2, BinS);
Ok := FormatString("%'05s", OutBinS, BinS);
WriteString(OutBinS);
WriteInt(D, 4);
WriteLn;
END
END GrayCode.
</syntaxhighlight>
{{out}}
<pre>
decimal binary gray decoded
0 00000 00000 00000 0
1 00001 00001 00001 1
2 00010 00011 00010 2
3 00011 00010 00011 3
4 00100 00110 00100 4
5 00101 00111 00101 5
6 00110 00101 00110 6
7 00111 00100 00111 7
8 01000 01100 01000 8
9 01001 01101 01001 9
10 01010 01111 01010 10
11 01011 01110 01011 11
12 01100 01010 01100 12
13 01101 01011 01101 13
14 01110 01001 01110 14
15 01111 01000 01111 15
16 10000 11000 10000 16
17 10001 11001 10001 17
18 10010 11011 10010 18
19 10011 11010 10011 19
20 10100 11110 10100 20
21 10101 11111 10101 21
22 10110 11101 10110 22
23 10111 11100 10111 23
24 11000 10100 11000 24
25 11001 10101 11001 25
26 11010 10111 11010 26
27 11011 10110 11011 27
28 11100 10010 11100 28
29 11101 10011 11101 29
30 11110 10001 11110 30
31 11111 10000 11111 31
</pre>
 
=={{header|Nim}}==
Line 4,366 ⟶ 5,296:
</pre>
 
=={{header|PowerBASICPL/M}}==
<syntaxhighlight lang="powerbasicplm">function gray%(byval n%)100H:
gray%=n% xor (n%\2)
end function
 
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
function igray%(byval n%)
EXIT: PROCEDURE; GO TO 0; END EXIT;
r%=0
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
while n%>0
r%=r% xor n%
shift right n%,1
wend
igray%=r%
end function
 
PRINT$NUM: PROCEDURE (N, BASE);
print " N GRAY INV"
DECLARE S (17) BYTE INITIAL ('................$');
for n%=0 to 31
DECLARE (N, P) ADDRESS, (DGT BASED P, BASE) BYTE;
g%=gray%(n%)
P = .S(16);
print bin$(n%);" ";bin$(g%);" ";bin$(igray%(g%))
DIGIT:
next</syntaxhighlight>
P = P - 1;
DGT = N MOD BASE + '0';
N = N / BASE;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUM;
 
GRAY$ENCODE: PROCEDURE (N) BYTE;
DECLARE N BYTE;
RETURN N XOR SHR(N, 1);
END GRAY$ENCODE;
 
GRAY$DECODE: PROCEDURE (N) BYTE;
DECLARE (N, R, I) BYTE;
R = N;
DO WHILE (N := SHR(N,1)) > 0;
R = R XOR N;
END;
RETURN R;
END GRAY$DECODE;
 
DECLARE (I, G) BYTE;
DO I = 0 TO 31;
CALL PRINT$NUM(I, 10);
CALL PRINT(.(':',9,'$'));
CALL PRINT$NUM(I, 2);
CALL PRINT(.(9,'=>',9,'$'));
CALL PRINT$NUM(G := GRAY$ENCODE(I), 2);
CALL PRINT(.(9,'=>',9,'$'));
CALL PRINT$NUM(GRAY$DECODE(G), 10);
CALL PRINT(.(10,13,'$'));
END;
CALL EXIT;
EOF</syntaxhighlight>
{{out}}
<pre>0: 0 => 0 => 0
1: 1 => 1 => 1
2: 10 => 11 => 2
3: 11 => 10 => 3
4: 100 => 110 => 4
5: 101 => 111 => 5
6: 110 => 101 => 6
7: 111 => 100 => 7
8: 1000 => 1100 => 8
9: 1001 => 1101 => 9
10: 1010 => 1111 => 10
11: 1011 => 1110 => 11
12: 1100 => 1010 => 12
13: 1101 => 1011 => 13
14: 1110 => 1001 => 14
15: 1111 => 1000 => 15
16: 10000 => 11000 => 16
17: 10001 => 11001 => 17
18: 10010 => 11011 => 18
19: 10011 => 11010 => 19
20: 10100 => 11110 => 20
21: 10101 => 11111 => 21
22: 10110 => 11101 => 22
23: 10111 => 11100 => 23
24: 11000 => 10100 => 24
25: 11001 => 10101 => 25
26: 11010 => 10111 => 26
27: 11011 => 10110 => 27
28: 11100 => 10010 => 28
29: 11101 => 10011 => 29
30: 11110 => 10001 => 30
31: 11111 => 10000 => 31</pre>
 
=={{header|Prolog}}==
 
=== Codecs ===
The encoding and decoding predicates are simple and will work
Line 4,482 ⟶ 5,471:
30 11110 10001 11110 30
31 11111 10000 11111 31</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">Procedure.i gray_encode(n)
ProcedureReturn n ! (n >> 1)
EndProcedure
 
Procedure.i gray_decode(g)
Protected bit = 1 << (8 * SizeOf(Integer) - 2)
Protected b = g & bit, p = b >> 1
While bit > 1
bit >> 1
b | (p ! (g & bit))
p = (b & bit) >> 1
Wend
ProcedureReturn b
EndProcedure
 
If OpenConsole()
PrintN("Number Gray Binary Decoded")
Define i, n
For i = 0 To 31
g = gray_encode(i)
Print(RSet(Str(i), 2, "0") + Space(5))
Print(RSet(Bin(g, #PB_Byte), 5, "0") + Space(2))
n = gray_decode(g)
Print(RSet(Bin(n, #PB_Byte), 5, "0") + Space(3))
PrintN(RSet(Str(n), 2, "0"))
Next
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</syntaxhighlight>
{{out}}
<pre>Number Gray Binary Decoded
00 00000 00000 00
01 00001 00001 01
02 00011 00010 02
03 00010 00011 03
04 00110 00100 04
05 00111 00101 05
06 00101 00110 06
07 00100 00111 07
08 01100 01000 08
09 01101 01001 09
10 01111 01010 10
11 01110 01011 11
12 01010 01100 12
13 01011 01101 13
14 01001 01110 14
15 01000 01111 15
16 11000 10000 16
17 11001 10001 17
18 11011 10010 18
19 11010 10011 19
20 11110 10100 20
21 11111 10101 21
22 11101 10110 22
23 11100 10111 23
24 10100 11000 24
25 10101 11001 25
26 10111 11010 26
27 10110 11011 27
28 10010 11100 28
29 10011 11101 29
30 10001 11110 30
31 10000 11111 31</pre>
 
=={{header|Python}}==
 
===Python: on integers===
Works with python integers
Line 5,013 ⟶ 5,934:
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ #1 RR 0 ROT START RL NEXT AND #0 ≠
≫ ´'''BIT?'''´ STO
≪ # 1b 0 ROT START RR NEXT OR
≫ ‘'''STBIT'''’ STO
≪ DUP SR XOR
≫ ‘'''→GRAY'''’ STO
≪ → gray
≪ #0 IF gray 0 '''BIT?''' THEN 0 '''STBIT''' END
1 RCWS 1 - FOR b
IF gray b '''BIT?''' OVER b 1 - '''BIT?''' XOR THEN b '''STBIT''' END
NEXT
≫ ≫ ‘'''GRAY→'''’ STO
≪ { } 0 31 FOR n n R→B '''→GRAY''' + NEXT
{ } 1 3 PICK SIZE FOR g OVER g GET '''GRAY→''' + NEXT
≫ ''''SHOWG'''’ STO
|
''( #b n -- boolean )''
''( #b n -- #b )''
''( #b -- #g )''
''( #g -- #b )''
b(0) = g(0)
Loop on all other bits
b[i] = g[i] xor b[i-1]
|}
{{in}}
<pre>
SHOWG
</pre>
{{out}}
<pre>
2: { # 0b # 1b # 11b # 10b # 110b # 111b # 101b # 100b # 1100b # 1101b # 1111b # 1110b # 1010b # 1011b # 1001b # 1000b # 11000b # 11001b # 11011b # 11010b # 11110b # 11111b # 11101b # 11100b # 10100b # 10101b # 10111b # 10110b # 10010b # 10011b # 10001b # 10000b }
1: { # 0b # 1b # 10b # 11b # 100b # 101b # 110b # 111b # 1000b # 1001b # 1010b # 1011b # 1100b # 1101b # 1110b # 1111b # 10000b # 10001b # 10010b # 10011b # 10100b # 10101b # 10110b # 10111b # 11000b # 11001b # 11010b # 11011b # 11100b # 11101b # 11110b # 11111b }
</pre>
=={{header|Ruby}}==
<tt>Integer#from_gray</tt> has recursion so it can use each bit of the answer to compute the next bit.
Line 5,798 ⟶ 6,775:
</pre>
 
=={{header|VBScript}}==
 
<syntaxhighlight lang="vb">Function Encoder(ByVal n)
Encoder = n Xor (n \ 2)
End Function
 
Function Decoder(ByVal n)
Dim g : g = 0
Do While n > 0
g = g Xor n
n = n \ 2
Loop
Decoder = g
End Function
 
' Decimal to Binary
Function Dec2bin(ByVal n, ByVal length)
Dim i, strbin : strbin = ""
For i = 1 to 5
strbin = (n Mod 2) & strbin
n = n \ 2
Next
Dec2Bin = strbin
End Function
 
WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary")
For i = 0 to 31
encoded = Encoder(i)
decoded = Decoder(encoded)
WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5))
Next</syntaxhighlight>
{{Out}}
<pre style="overflow: auto; height: 20em;">Binary -> Gray Code -> Binary
00000 -> 00000 -> 00000
00001 -> 00001 -> 00001
00010 -> 00011 -> 00010
00011 -> 00010 -> 00011
00100 -> 00110 -> 00100
00101 -> 00111 -> 00101
00110 -> 00101 -> 00110
00111 -> 00100 -> 00111
01000 -> 01100 -> 01000
01001 -> 01101 -> 01001
01010 -> 01111 -> 01010
01011 -> 01110 -> 01011
01100 -> 01010 -> 01100
01101 -> 01011 -> 01101
01110 -> 01001 -> 01110
01111 -> 01000 -> 01111
10000 -> 11000 -> 10000
10001 -> 11001 -> 10001
10010 -> 11011 -> 10010
10011 -> 11010 -> 10011
10100 -> 11110 -> 10100
10101 -> 11111 -> 10101
10110 -> 11101 -> 10110
10111 -> 11100 -> 10111
11000 -> 10100 -> 11000
11001 -> 10101 -> 11001
11010 -> 10111 -> 11010
11011 -> 10110 -> 11011
11100 -> 10010 -> 11100
11101 -> 10011 -> 11101
11110 -> 10001 -> 11110
11111 -> 10000 -> 11111</pre>
 
=={{header|Verilog}}==
 
'''Function Based Approach:'''
 
Line 6,031 ⟶ 6,942:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "./fmt" for Fmt
 
var toGray = Fn.new { |n| n ^ (n>>1) }
Line 6,087 ⟶ 6,998:
30 11110 10001 11110
31 11111 10000 11111
</pre>
 
=={{header|XBasic}}==
{{trans|DWScript}}
Intrinsic function <code>BIN$</code> has been used.
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">' Gray code
PROGRAM "graycode"
VERSION "0.0001"
 
DECLARE FUNCTION Entry()
INTERNAL FUNCTION Encode(v&)
INTERNAL FUNCTION Decode(v&)
 
FUNCTION Entry()
PRINT "decimal binary gray decoded"
FOR i& = 0 TO 31
g& = Encode(i&)
d& = Decode(g&)
PRINT FORMAT$(" ##", i&); " "; BIN$(i&, 5); " "; BIN$(g&, 5);
PRINT " "; BIN$(d&, 5); FORMAT$(" ##", d&)
NEXT i&
END FUNCTION
 
FUNCTION Encode(v&)
END FUNCTION v& ^ (v& >> 1)
 
FUNCTION Decode(v&)
result& = 0
DO WHILE v& > 0
result& = result& ^ v&
v& = v& >> 1
LOOP
END FUNCTION result&
 
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
decimal binary gray decoded
0 00000 00000 00000 0
1 00001 00001 00001 1
2 00010 00011 00010 2
3 00011 00010 00011 3
4 00100 00110 00100 4
5 00101 00111 00101 5
6 00110 00101 00110 6
7 00111 00100 00111 7
8 01000 01100 01000 8
9 01001 01101 01001 9
10 01010 01111 01010 10
11 01011 01110 01011 11
12 01100 01010 01100 12
13 01101 01011 01101 13
14 01110 01001 01110 14
15 01111 01000 01111 15
16 10000 11000 10000 16
17 10001 11001 10001 17
18 10010 11011 10010 18
19 10011 11010 10011 19
20 10100 11110 10100 20
21 10101 11111 10101 21
22 10110 11101 10110 22
23 10111 11100 10111 23
24 11000 10100 11000 24
25 11001 10101 11001 25
26 11010 10111 11010 26
27 11011 10110 11011 27
28 11100 10010 11100 28
29 11101 10011 11101 29
30 11110 10001 11110 30
31 11111 10000 11111 31
</pre>
 
511

edits