Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
2
Task/Gray-code/00-META.yaml
Normal file
2
Task/Gray-code/00-META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Gray_code
|
||||
29
Task/Gray-code/00-TASK.txt
Normal file
29
Task/Gray-code/00-TASK.txt
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
[[wp:Gray code|Gray code]] is a form of binary encoding where transitions between consecutive numbers differ by only one bit. This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs. It is also useful for generating inputs for [[wp:Karnaugh map|Karnaugh maps]] in order from left to right or top to bottom.
|
||||
|
||||
Create functions to encode a number to and decode a number from Gray code.
|
||||
|
||||
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
|
||||
|
||||
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
|
||||
|
||||
Encoding (MSB is bit 0, b is binary, g is Gray code):
|
||||
|
||||
<pre>if b[i-1] = 1
|
||||
g[i] = not b[i]
|
||||
else
|
||||
g[i] = b[i]</pre>
|
||||
|
||||
Or:
|
||||
|
||||
<pre>g = b xor (b logically right shifted 1 time)</pre>
|
||||
|
||||
Decoding (MSB is bit 0, b is binary, g is Gray code):
|
||||
|
||||
<pre>b[0] = g[0]
|
||||
|
||||
for other bits:
|
||||
b[i] = g[i] xor b[i-1]</pre>
|
||||
|
||||
;Reference
|
||||
* [http://www.wisc-online.com/Objects/ViewObject.aspx?ID=IAU8307 Converting Between Gray and Binary Codes]. It includes step-by-step animations.
|
||||
|
||||
15
Task/Gray-code/11l/gray-code.11l
Normal file
15
Task/Gray-code/11l/gray-code.11l
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
F gray_encode(n)
|
||||
R n (+) n >> 1
|
||||
|
||||
F gray_decode(=n)
|
||||
V m = n >> 1
|
||||
L m != 0
|
||||
n (+)= m
|
||||
m >>= 1
|
||||
R n
|
||||
|
||||
print(‘DEC, BIN => GRAY => DEC’)
|
||||
L(i) 32
|
||||
V gray = gray_encode(i)
|
||||
V dec = gray_decode(gray)
|
||||
print(‘ #2, #. => #. => #2’.format(i, bin(i).zfill(5), bin(gray).zfill(5), dec))
|
||||
64
Task/Gray-code/8051-Assembly/gray-code.8051
Normal file
64
Task/Gray-code/8051-Assembly/gray-code.8051
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
.equ cin, 0x0032
|
||||
.equ cout, 0x0030
|
||||
.equ phex, 0x0034
|
||||
.equ phex16, 0x0036
|
||||
.equ nl, 0x0048
|
||||
|
||||
.org 0x2000
|
||||
|
||||
main:
|
||||
mov r7, #0
|
||||
|
||||
next:
|
||||
mov a, r7
|
||||
lcall phex
|
||||
|
||||
mov a, #' '
|
||||
lcall cout
|
||||
|
||||
mov a, r7
|
||||
acall genc
|
||||
lcall phex
|
||||
|
||||
mov r6, a
|
||||
|
||||
mov a, #' '
|
||||
lcall cout
|
||||
|
||||
mov a, r6
|
||||
acall gdec
|
||||
lcall phex
|
||||
|
||||
lcall nl
|
||||
|
||||
inc r7
|
||||
cjne r7, #0, next
|
||||
|
||||
lcall cin
|
||||
|
||||
ljmp 0x0000
|
||||
|
||||
;--------
|
||||
genc:
|
||||
mov r0, a
|
||||
clr c
|
||||
rrc a
|
||||
xrl a, r0
|
||||
ret
|
||||
;--------
|
||||
|
||||
;--------
|
||||
gdec:
|
||||
mov r0, a
|
||||
gdec_shift_xor:
|
||||
clr c
|
||||
rrc a
|
||||
jz gdec_out
|
||||
xch a, r0
|
||||
xrl a, r0
|
||||
xch a, r0
|
||||
sjmp gdec_shift_xor
|
||||
gdec_out:
|
||||
xch a, r0
|
||||
ret
|
||||
;--------
|
||||
84
Task/Gray-code/8080-Assembly/gray-code.8080
Normal file
84
Task/Gray-code/8080-Assembly/gray-code.8080
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
org 100h
|
||||
xra a ; set A=0
|
||||
loop: push psw ; print number as decimal
|
||||
call decout
|
||||
call padding ; print padding
|
||||
pop psw
|
||||
push psw
|
||||
call binout ; print number as binary
|
||||
call padding
|
||||
pop psw
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
mov b,a ; gray encode
|
||||
ana a ; clear carry
|
||||
rar ; shift right
|
||||
xra b ; xor the original
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
push psw
|
||||
call binout ; print gray number as binary
|
||||
call padding
|
||||
pop psw
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
mov b,a ; gray decode
|
||||
decode: ana a ; clear carry
|
||||
jz done ; when no more bits are left, stop
|
||||
rar ; shift right
|
||||
mov c,a ; keep that value
|
||||
xra b ; xor into output value
|
||||
mov b,a ; that is the output value
|
||||
mov a,c ; restore intermediate
|
||||
jmp decode ; do next bit
|
||||
done: mov a,b ; give output value
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
push psw
|
||||
call binout ; print decoded number as binary
|
||||
call padding
|
||||
pop psw
|
||||
push psw
|
||||
call decout ; print decoded number as decimal
|
||||
lxi d,nl
|
||||
call strout
|
||||
pop psw
|
||||
inr a ; next number
|
||||
ani 1fh ; are we there yet?
|
||||
jnz loop ; if not, do next number
|
||||
ret
|
||||
;; Print A as two-digit number
|
||||
decout: mvi c,10
|
||||
call dgtout
|
||||
mvi c,1
|
||||
dgtout: mvi e,'0' - 1
|
||||
dgtloop: inr e
|
||||
sub c
|
||||
jnc dgtloop
|
||||
add c
|
||||
push psw
|
||||
mvi c,2
|
||||
call 5
|
||||
pop psw
|
||||
ret
|
||||
;; Print A as five-bit binary number
|
||||
binout: ani 1fh
|
||||
ral
|
||||
ral
|
||||
ral
|
||||
mvi c,5
|
||||
binloop: ral
|
||||
push psw
|
||||
push b
|
||||
mvi c,2
|
||||
mvi a,0
|
||||
aci '0'
|
||||
mov e,a
|
||||
call 5
|
||||
pop b
|
||||
pop psw
|
||||
dcr c
|
||||
jnz binloop
|
||||
ret
|
||||
;; Print padding
|
||||
padding: lxi d,arrow
|
||||
strout: mvi c,9
|
||||
jmp 5
|
||||
arrow: db ' ==> $'
|
||||
nl: db 13,10,'$'
|
||||
12
Task/Gray-code/ALGOL-68/gray-code.alg
Normal file
12
Task/Gray-code/ALGOL-68/gray-code.alg
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
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
|
||||
BEGIN
|
||||
BITS b := g, mask := g SHR 1;
|
||||
WHILE mask /= 2r0 DO b := b XOR mask; mask := mask SHR 1 OD;
|
||||
b
|
||||
END;
|
||||
FOR i FROM 0 TO 31 DO
|
||||
printf (($zd, ": ", 2(2r5d, " >= "), 2r5dl$, i, BIN i, GRAY BIN i, YARG GRAY BIN i))
|
||||
OD
|
||||
END
|
||||
2
Task/Gray-code/APL/gray-code-1.apl
Normal file
2
Task/Gray-code/APL/gray-code-1.apl
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
N←5
|
||||
({(0,⍵)⍪1,⊖⍵}⍣N)(1 0⍴⍬)
|
||||
5
Task/Gray-code/APL/gray-code-2.apl
Normal file
5
Task/Gray-code/APL/gray-code-2.apl
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
N←5
|
||||
grayEncode←{a≠N↑(0,a←(N⍴2)⊤⍵)}
|
||||
grayDecode←{2⊥≠⌿N N↑N(2×N)⍴⍵,0,N⍴0}
|
||||
|
||||
grayEncode 19
|
||||
37
Task/Gray-code/AWK/gray-code.awk
Normal file
37
Task/Gray-code/AWK/gray-code.awk
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
# Tested using GAWK
|
||||
|
||||
function bits2str(bits, data, mask)
|
||||
{
|
||||
# Source: https://www.gnu.org/software/gawk/manual/html_node/Bitwise-Functions.html
|
||||
if (bits == 0)
|
||||
return "0"
|
||||
|
||||
mask = 1
|
||||
for (; bits != 0; bits = rshift(bits, 1))
|
||||
data = (and(bits, mask) ? "1" : "0") data
|
||||
|
||||
while ((length(data) % 8) != 0)
|
||||
data = "0" data
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
function gray_encode(n){
|
||||
# Source: https://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code
|
||||
return xor(n,rshift(n,1))
|
||||
}
|
||||
|
||||
function gray_decode(n){
|
||||
# Source: https://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code
|
||||
mask = rshift(n,1)
|
||||
while(mask != 0){
|
||||
n = xor(n,mask)
|
||||
mask = rshift(mask,1)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
BEGIN{
|
||||
for (i=0; i < 32; i++)
|
||||
printf "%-3s => %05d => %05d => %05d\n",i, bits2str(i),bits2str(gray_encode(i)), bits2str(gray_decode(gray_encode(i)))
|
||||
}
|
||||
58
Task/Gray-code/Action-/gray-code.action
Normal file
58
Task/Gray-code/Action-/gray-code.action
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
PROC ToBinaryStr(BYTE n CHAR ARRAY s)
|
||||
BYTE i
|
||||
|
||||
s(0)=8 i=8
|
||||
SetBlock(s+1,8,'0)
|
||||
WHILE n
|
||||
DO
|
||||
s(i)=(n&1)+'0
|
||||
n==RSH 1
|
||||
i==-1
|
||||
OD
|
||||
RETURN
|
||||
|
||||
PROC PrintB2(BYTE n)
|
||||
IF n<10 THEN Put(32) FI
|
||||
PrintB(n)
|
||||
RETURN
|
||||
|
||||
PROC PrintBin5(BYTE n)
|
||||
CHAR ARRAY s(9),sub(6)
|
||||
|
||||
ToBinaryStr(n,s)
|
||||
SCopyS(sub,s,4,s(0))
|
||||
Print(sub)
|
||||
RETURN
|
||||
|
||||
BYTE FUNC Encode(BYTE n)
|
||||
RETURN (n XOR (n RSH 1))
|
||||
|
||||
BYTE FUNC Decode(BYTE n)
|
||||
BYTE res
|
||||
|
||||
res=n
|
||||
DO
|
||||
n==RSH 1
|
||||
IF n THEN
|
||||
res==XOR n
|
||||
ELSE
|
||||
EXIT
|
||||
FI
|
||||
OD
|
||||
RETURN (res)
|
||||
|
||||
PROC Main()
|
||||
BYTE i,g,b
|
||||
CHAR ARRAY sep=" -> "
|
||||
|
||||
FOR i=0 TO 31
|
||||
DO
|
||||
PrintB2(i) Print(sep)
|
||||
PrintBin5(i) Print(sep)
|
||||
g=Encode(i)
|
||||
PrintBin5(g) Print(sep)
|
||||
b=Decode(g)
|
||||
PrintBin5(b) Print(sep)
|
||||
PrintB2(b) PutE()
|
||||
OD
|
||||
RETURN
|
||||
47
Task/Gray-code/Ada/gray-code.ada
Normal file
47
Task/Gray-code/Ada/gray-code.ada
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
with Ada.Text_IO, Interfaces;
|
||||
use Ada.Text_IO, Interfaces;
|
||||
|
||||
procedure Gray is
|
||||
|
||||
Bits : constant := 5; -- Change only this line for 6 or 7-bit encodings
|
||||
subtype Values is Unsigned_8 range 0 .. 2 ** Bits - 1;
|
||||
package Values_Io is new Ada.Text_IO.Modular_IO (Values);
|
||||
|
||||
function Encode (Binary : Values) return Values is
|
||||
begin
|
||||
return Binary xor Shift_Right (Binary, 1);
|
||||
end Encode;
|
||||
pragma Inline (Encode);
|
||||
|
||||
function Decode (Gray : Values) return Values is
|
||||
Binary, Bit : Values;
|
||||
Mask : Values := 2 ** (Bits - 1);
|
||||
begin
|
||||
Bit := Gray and Mask;
|
||||
Binary := Bit;
|
||||
for I in 2 .. Bits loop
|
||||
Bit := Shift_Right (Bit, 1);
|
||||
Mask := Shift_Right (Mask, 1);
|
||||
Bit := (Gray and Mask) xor Bit;
|
||||
Binary := Binary + Bit;
|
||||
end loop;
|
||||
return Binary;
|
||||
end Decode;
|
||||
pragma Inline (Decode);
|
||||
|
||||
HT : constant Character := Character'Val (9);
|
||||
J : Values;
|
||||
begin
|
||||
Put_Line ("Num" & HT & "Binary" & HT & HT & "Gray" & HT & HT & "decoded");
|
||||
for I in Values'Range loop
|
||||
J := Encode (I);
|
||||
Values_Io.Put (I, 4);
|
||||
Put (": " & HT);
|
||||
Values_Io.Put (I, Bits + 2, 2);
|
||||
Put (" =>" & HT);
|
||||
Values_Io.Put (J, Bits + 2, 2);
|
||||
Put (" => " & HT);
|
||||
Values_Io.Put (Decode (J), 4);
|
||||
New_Line;
|
||||
end loop;
|
||||
end Gray;
|
||||
18
Task/Gray-code/Aime/gray-code-1.aime
Normal file
18
Task/Gray-code/Aime/gray-code-1.aime
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
integer
|
||||
gray_encode(integer n)
|
||||
{
|
||||
n ^ (n >> 1);
|
||||
}
|
||||
|
||||
integer
|
||||
gray_decode(integer n)
|
||||
{
|
||||
integer p;
|
||||
|
||||
p = n;
|
||||
while (n >>= 1) {
|
||||
p ^= n;
|
||||
}
|
||||
|
||||
p;
|
||||
}
|
||||
24
Task/Gray-code/Aime/gray-code-2.aime
Normal file
24
Task/Gray-code/Aime/gray-code-2.aime
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
integer
|
||||
main(void)
|
||||
{
|
||||
integer i, g, b;
|
||||
|
||||
i = 0;
|
||||
while (i < 32) {
|
||||
g = gray_encode(i);
|
||||
b = gray_decode(g);
|
||||
o_winteger(2, i);
|
||||
o_text(": ");
|
||||
o_fxinteger(5, 2, i);
|
||||
o_text(" => ");
|
||||
o_fxinteger(5, 2, g);
|
||||
o_text(" => ");
|
||||
o_fxinteger(5, 2, b);
|
||||
o_text(": ");
|
||||
o_winteger(2, b);
|
||||
o_byte('\n');
|
||||
i += 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
31
Task/Gray-code/Amazing-Hopper/gray-code.hopper
Normal file
31
Task/Gray-code/Amazing-Hopper/gray-code.hopper
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
#proto GrayEncode(_X_)
|
||||
#synon _GrayEncode *getGrayEncode
|
||||
#proto GrayDecode(_X_)
|
||||
#synon _GrayDecode *getGrayDecode
|
||||
|
||||
#include <hbasic.h>
|
||||
|
||||
Begin
|
||||
Gray=0
|
||||
SizeBin(4) // size 5 bits: 0->4
|
||||
Take (" # BINARY GRAY DECODE\n")
|
||||
Take ("------------------------------\n"), and Print It
|
||||
For Up( i := 0, 31, 1)
|
||||
Print( LPad$(" ",2,Str$(i))," => ", Bin$(i)," => ")
|
||||
get Gray Encode(i) and Copy to (Gray), get Binary; then Take(" => ")
|
||||
now get Gray Decode( Gray ), get Binary, and Print It with a Newl
|
||||
Next
|
||||
End
|
||||
|
||||
Subrutines
|
||||
|
||||
Gray Encode(n)
|
||||
Return (XorBit( RShift(1,n), n ))
|
||||
|
||||
Gray Decode(n)
|
||||
p = n
|
||||
While ( n )
|
||||
n >>= 1
|
||||
p != n
|
||||
Wend
|
||||
Return (p)
|
||||
22
Task/Gray-code/Arturo/gray-code.arturo
Normal file
22
Task/Gray-code/Arturo/gray-code.arturo
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
toGray: function [n]-> xor n shr n 1
|
||||
fromGray: function [n][
|
||||
p: n
|
||||
while [n > 0][
|
||||
n: shr n 1
|
||||
p: xor p n
|
||||
]
|
||||
return p
|
||||
]
|
||||
|
||||
loop 0..31 'num [
|
||||
encoded: toGray num
|
||||
decoded: fromGray encoded
|
||||
|
||||
print [
|
||||
pad to :string num 2 ":"
|
||||
pad as.binary num 5 "=>"
|
||||
pad as.binary encoded 5 "=>"
|
||||
pad as.binary decoded 5 ":"
|
||||
pad to :string decoded 2
|
||||
]
|
||||
]
|
||||
23
Task/Gray-code/AutoHotkey/gray-code.ahk
Normal file
23
Task/Gray-code/AutoHotkey/gray-code.ahk
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
gray_encode(n){
|
||||
return n ^ (n >> 1)
|
||||
}
|
||||
|
||||
gray_decode(n){
|
||||
p := n
|
||||
while (n >>= 1)
|
||||
p ^= n
|
||||
return p
|
||||
}
|
||||
|
||||
BinString(n){
|
||||
Loop 5
|
||||
If ( n & ( 1 << (A_Index-1) ) )
|
||||
o := "1" . o
|
||||
else o := "0" . o
|
||||
return o
|
||||
}
|
||||
|
||||
Loop 32
|
||||
n:=A_Index-1, out .= n " : " BinString(n) " => " BinString(e:=gray_encode(n))
|
||||
. " => " BinString(gray_decode(e)) " => " BinString(n) "`n"
|
||||
MsgBox % clipboard := out
|
||||
24
Task/Gray-code/BASIC/gray-code.basic
Normal file
24
Task/Gray-code/BASIC/gray-code.basic
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
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
|
||||
15
Task/Gray-code/BBC-BASIC/gray-code.basic
Normal file
15
Task/Gray-code/BBC-BASIC/gray-code.basic
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
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%
|
||||
22
Task/Gray-code/BCPL/gray-code.bcpl
Normal file
22
Task/Gray-code/BCPL/gray-code.bcpl
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
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)
|
||||
62
Task/Gray-code/Batch-File/gray-code.bat
Normal file
62
Task/Gray-code/Batch-File/gray-code.bat
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
:: Gray Code Task from Rosetta Code
|
||||
:: Batch File Implementation
|
||||
|
||||
@echo off
|
||||
rem -------------- define batch file macros with parameters appended
|
||||
rem more info: https://www.dostips.com/forum/viewtopic.php?f=3&t=2518
|
||||
setlocal disabledelayedexpansion % == required for macro ==%
|
||||
(set \n=^^^
|
||||
%== this creates escaped line feed for macro ==%
|
||||
)
|
||||
|
||||
rem convert to binary (unsigned)
|
||||
rem argument: natnum bitlength outputvar
|
||||
rem note: if natnum is negative, then !outputvar! is empty
|
||||
set tobinary=for %%# in (1 2) do if %%#==2 ( %\n%
|
||||
for /f "tokens=1,2,3" %%a in ("!args!") do ( %\n%
|
||||
set "natnum=%%a"^&set "bitlength=%%b"^&set "outputvar=%%c") %\n%
|
||||
set "!outputvar!=" %\n%
|
||||
if !natnum! geq 0 ( %\n%
|
||||
set "currnum=!natnum!" %\n%
|
||||
for /l %%m in (1,1,!bitlength!) do ( %\n%
|
||||
set /a "bit=!currnum!%%2" %\n%
|
||||
for %%v in (!outputvar!) do set "!outputvar!=!bit!!%%v!" %\n%
|
||||
set /a "currnum/=2" %\n%
|
||||
) %\n%
|
||||
) %\n%
|
||||
) else set args=
|
||||
|
||||
goto :main-thing %== jump to the main thing ==%
|
||||
rem -------------- usual "call" sections
|
||||
rem the sad disadvantage of using these is that they are slow (TnT)
|
||||
|
||||
rem gray code encoder
|
||||
rem argument: natnum outputvar
|
||||
:encoder
|
||||
set /a "%~2=%~1^(%~1>>1)"
|
||||
goto :eof
|
||||
|
||||
rem gray code decoder
|
||||
rem argument: natnum outputvar
|
||||
:decoder
|
||||
set "inp=%~1" & set "%~2=0"
|
||||
:while-loop-1
|
||||
if %inp% gtr 0 (
|
||||
set /a "%~2^=%inp%, inp>>=1"
|
||||
goto while-loop-1
|
||||
)
|
||||
goto :eof
|
||||
|
||||
rem -------------- main thing
|
||||
:main-thing
|
||||
setlocal enabledelayedexpansion
|
||||
echo(# -^> bin -^> enc -^> dec
|
||||
for /l %%n in (0,1,31) do (
|
||||
%tobinary% %%n 5 bin
|
||||
call :encoder "%%n" "enc"
|
||||
%tobinary% !enc! 5 gray
|
||||
call :decoder "!enc!" "dec"
|
||||
%tobinary% !dec! 5 rebin
|
||||
echo(%%n -^> !bin! -^> !gray! -^> !rebin!
|
||||
)
|
||||
exit /b 0
|
||||
46
Task/Gray-code/Bc/gray-code.bc
Normal file
46
Task/Gray-code/Bc/gray-code.bc
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
scale = 0 /* to use integer division */
|
||||
|
||||
/* encode Gray code */
|
||||
define e(i) {
|
||||
auto h, r
|
||||
|
||||
if (i <= 0) return 0
|
||||
h = i / 2
|
||||
r = e(h) * 2 /* recurse */
|
||||
if (h % 2 != i % 2) r += 1 /* xor low bits of h, i */
|
||||
return r
|
||||
}
|
||||
|
||||
/* decode Gray code */
|
||||
define d(i) {
|
||||
auto h, r
|
||||
|
||||
if (i <= 0) return 0
|
||||
h = d(i / 2) /* recurse */
|
||||
r = h * 2
|
||||
if (h % 2 != i % 2) r += 1 /* xor low bits of h, i */
|
||||
return r
|
||||
}
|
||||
|
||||
|
||||
/* print i as 5 binary digits */
|
||||
define p(i) {
|
||||
auto d, d[]
|
||||
|
||||
for (d = 0; d <= 4; d++) {
|
||||
d[d] = i % 2
|
||||
i /= 2
|
||||
}
|
||||
for (d = 4; d >= 0; d--) {
|
||||
if(d[d] == 0) "0"
|
||||
if(d[d] == 1) "1"
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0; i < 32; i++) {
|
||||
/* original */ t = p(i); " => "
|
||||
/* encoded */ e = e(i); t = p(e); " => "
|
||||
/* decoded */ d = d(e); t = p(d); "
|
||||
"
|
||||
}
|
||||
quit
|
||||
38
Task/Gray-code/C++/gray-code.cpp
Normal file
38
Task/Gray-code/C++/gray-code.cpp
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
#include <bitset>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <assert.h>
|
||||
|
||||
uint32_t gray_encode(uint32_t b)
|
||||
{
|
||||
return b ^ (b >> 1);
|
||||
}
|
||||
|
||||
uint32_t gray_decode(uint32_t g)
|
||||
{
|
||||
for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)
|
||||
{
|
||||
if (g & bit) g ^= bit >> 1;
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
std::string to_binary(int value) // utility function
|
||||
{
|
||||
const std::bitset<32> bs(value);
|
||||
const std::string str(bs.to_string());
|
||||
const size_t pos(str.find('1'));
|
||||
return pos == std::string::npos ? "0" : str.substr(pos);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout << "Number\tBinary\tGray\tDecoded\n";
|
||||
for (uint32_t n = 0; n < 32; ++n)
|
||||
{
|
||||
uint32_t g = gray_encode(n);
|
||||
assert(gray_decode(g) == n);
|
||||
|
||||
std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n";
|
||||
}
|
||||
}
|
||||
23
Task/Gray-code/C-sharp/gray-code.cs
Normal file
23
Task/Gray-code/C-sharp/gray-code.cs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
using System;
|
||||
|
||||
public class Gray {
|
||||
public static ulong grayEncode(ulong n) {
|
||||
return n^(n>>1);
|
||||
}
|
||||
|
||||
public static ulong grayDecode(ulong n) {
|
||||
ulong i=1<<8*64-2; //long is 64-bit
|
||||
ulong p, b=p=n&i;
|
||||
|
||||
while((i>>=1)>0)
|
||||
b|=p=n&i^p>>1;
|
||||
return b;
|
||||
}
|
||||
|
||||
public static void Main(string[] args) {
|
||||
Console.WriteLine("Number\tBinary\tGray\tDecoded");
|
||||
for(ulong i=0;i<32;i++) {
|
||||
Console.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}", i, Convert.ToString((long)i, 2), Convert.ToString((long)grayEncode(i), 2), grayDecode(grayEncode(i))));
|
||||
}
|
||||
}
|
||||
}
|
||||
9
Task/Gray-code/C/gray-code-1.c
Normal file
9
Task/Gray-code/C/gray-code-1.c
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
int gray_encode(int n) {
|
||||
return n ^ (n >> 1);
|
||||
}
|
||||
|
||||
int gray_decode(int n) {
|
||||
int p = n;
|
||||
while (n >>= 1) p ^= n;
|
||||
return p;
|
||||
}
|
||||
24
Task/Gray-code/C/gray-code-2.c
Normal file
24
Task/Gray-code/C/gray-code-2.c
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
#include <stdio.h>
|
||||
|
||||
/* Simple bool formatter, only good on range 0..31 */
|
||||
void fmtbool(int n, char *buf) {
|
||||
char *b = buf + 5;
|
||||
*b=0;
|
||||
do {
|
||||
*--b = '0' + (n & 1);
|
||||
n >>= 1;
|
||||
} while (b != buf);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int i,g,b;
|
||||
char bi[6],bg[6],bb[6];
|
||||
|
||||
for (i=0 ; i<32 ; i++) {
|
||||
g = gray_encode(i);
|
||||
b = gray_decode(g);
|
||||
fmtbool(i,bi); fmtbool(g,bg); fmtbool(b,bb);
|
||||
printf("%2d : %5s => %5s => %5s : %2d\n", i, bi, bg, bb, b);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
10
Task/Gray-code/CoffeeScript/gray-code.coffee
Normal file
10
Task/Gray-code/CoffeeScript/gray-code.coffee
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
gray_encode = (n) ->
|
||||
n ^ (n >> 1)
|
||||
|
||||
gray_decode = (g) ->
|
||||
n = g
|
||||
n ^= g while g >>= 1
|
||||
n
|
||||
|
||||
for i in [0..32]
|
||||
console.log gray_decode gray_encode(i)
|
||||
11
Task/Gray-code/Common-Lisp/gray-code.lisp
Normal file
11
Task/Gray-code/Common-Lisp/gray-code.lisp
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
(defun gray-encode (n)
|
||||
(logxor n (ash n -1)))
|
||||
|
||||
(defun gray-decode (n)
|
||||
(do ((p n (logxor p n)))
|
||||
((zerop n) p)
|
||||
(setf n (ash n -1))))
|
||||
|
||||
(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)))
|
||||
51
Task/Gray-code/Component-Pascal/gray-code.pas
Normal file
51
Task/Gray-code/Component-Pascal/gray-code.pas
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
MODULE GrayCodes;
|
||||
IMPORT StdLog,SYSTEM;
|
||||
|
||||
PROCEDURE Encode*(i: INTEGER; OUT x: INTEGER);
|
||||
VAR
|
||||
j: INTEGER;
|
||||
s,r: SET;
|
||||
BEGIN
|
||||
s := BITS(i);j := MAX(SET);
|
||||
WHILE (j >= 0) & ~(j IN s) DO DEC(j) END;
|
||||
r := {};IF j >= 0 THEN INCL(r,j) END;
|
||||
WHILE j > 0 DO
|
||||
IF ((j IN s) & ~(j - 1 IN s)) OR (~(j IN s) & (j - 1 IN s)) THEN INCL(r,j-1) END;
|
||||
DEC(j)
|
||||
END;
|
||||
x := SYSTEM.VAL(INTEGER,r)
|
||||
END Encode;
|
||||
|
||||
PROCEDURE Decode*(x: INTEGER; OUT i: INTEGER);
|
||||
VAR
|
||||
j: INTEGER;
|
||||
s,r: SET;
|
||||
BEGIN
|
||||
s := BITS(x);r:={};j := MAX(SET);
|
||||
WHILE (j >= 0) & ~(j IN s) DO DEC(j) END;
|
||||
IF j >= 0 THEN INCL(r,j) END;
|
||||
WHILE j > 0 DO
|
||||
IF ((j IN r) & ~(j - 1 IN s)) OR (~(j IN r) & (j - 1 IN s)) THEN INCL(r,j-1) END;
|
||||
DEC(j)
|
||||
END;
|
||||
i := SYSTEM.VAL(INTEGER,r);
|
||||
END Decode;
|
||||
|
||||
|
||||
PROCEDURE Do*;
|
||||
VAR
|
||||
grayCode,binCode: INTEGER;
|
||||
i: INTEGER;
|
||||
BEGIN
|
||||
StdLog.String(" i ");StdLog.String(" bin code ");StdLog.String(" gray code ");StdLog.Ln;
|
||||
StdLog.String("---");StdLog.String(" ----------------");StdLog.String(" ---------------");StdLog.Ln;
|
||||
FOR i := 0 TO 32 DO;
|
||||
Encode(i,grayCode);Decode(grayCode,binCode);
|
||||
StdLog.IntForm(i,10,3,' ',FALSE);
|
||||
StdLog.IntForm(binCode,2,16,' ',TRUE);
|
||||
StdLog.IntForm(grayCode,2,16,' ',TRUE);
|
||||
StdLog.Ln;
|
||||
END
|
||||
END Do;
|
||||
|
||||
END GrayCodes.
|
||||
45
Task/Gray-code/Cowgol/gray-code.cowgol
Normal file
45
Task/Gray-code/Cowgol/gray-code.cowgol
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
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;
|
||||
12
Task/Gray-code/Crystal/gray-code-1.crystal
Normal file
12
Task/Gray-code/Crystal/gray-code-1.crystal
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
def gray_encode(bin)
|
||||
bin ^ (bin >> 1)
|
||||
end
|
||||
|
||||
def gray_decode(gray)
|
||||
bin = gray
|
||||
while gray > 0
|
||||
gray >>= 1
|
||||
bin ^= gray
|
||||
end
|
||||
bin
|
||||
end
|
||||
5
Task/Gray-code/Crystal/gray-code-2.crystal
Normal file
5
Task/Gray-code/Crystal/gray-code-2.crystal
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
(0..31).each do |n|
|
||||
gr = gray_encode n
|
||||
bin = gray_decode gr
|
||||
printf "%2d : %05b => %05b => %05b : %2d\n", n, n, gr, bin, bin
|
||||
end
|
||||
22
Task/Gray-code/D/gray-code-1.d
Normal file
22
Task/Gray-code/D/gray-code-1.d
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
uint grayEncode(in uint n) pure nothrow @nogc {
|
||||
return n ^ (n >> 1);
|
||||
}
|
||||
|
||||
uint grayDecode(uint n) pure nothrow @nogc {
|
||||
auto p = n;
|
||||
while (n >>= 1)
|
||||
p ^= n;
|
||||
return p;
|
||||
}
|
||||
|
||||
void main() {
|
||||
import std.stdio;
|
||||
|
||||
" N N2 enc dec2 dec".writeln;
|
||||
foreach (immutable n; 0 .. 32) {
|
||||
immutable g = n.grayEncode;
|
||||
immutable d = g.grayDecode;
|
||||
writefln("%2d: %5b => %5b => %5b: %2d", n, n, g, d, d);
|
||||
assert(d == n);
|
||||
}
|
||||
}
|
||||
38
Task/Gray-code/D/gray-code-2.d
Normal file
38
Task/Gray-code/D/gray-code-2.d
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import std.stdio, std.algorithm;
|
||||
|
||||
T[] gray(int N : 1, T)() pure nothrow {
|
||||
return [T(0), 1];
|
||||
}
|
||||
|
||||
/// Recursively generate gray encoding mapping table.
|
||||
T[] gray(int N, T)() pure nothrow if (N <= T.sizeof * 8) {
|
||||
enum T M = T(2) ^^ (N - 1);
|
||||
T[] g = gray!(N - 1, T)();
|
||||
foreach (immutable i; 0 .. M)
|
||||
g ~= M + g[M - i - 1];
|
||||
return g;
|
||||
}
|
||||
|
||||
T[][] grayDict(int N, T)() pure nothrow {
|
||||
T[][] dict = [gray!(N, T)(), [0]];
|
||||
// Append inversed gray encoding mapping.
|
||||
foreach (immutable i; 1 .. dict[0].length)
|
||||
dict[1] ~= cast(T)countUntil(dict[0], i);
|
||||
return dict;
|
||||
}
|
||||
|
||||
enum M { Encode = 0, Decode = 1 }
|
||||
|
||||
T gray(int N, T)(in T n, in int mode=M.Encode) pure nothrow {
|
||||
// Generated at compile time.
|
||||
enum dict = grayDict!(N, T)();
|
||||
return dict[mode][n];
|
||||
}
|
||||
|
||||
void main() {
|
||||
foreach (immutable i; 0 .. 32) {
|
||||
immutable encoded = gray!(5)(i, M.Encode);
|
||||
immutable decoded = gray!(5)(encoded, M.Decode);
|
||||
writefln("%2d: %5b => %5b : %2d", i, i, encoded, decoded);
|
||||
}
|
||||
}
|
||||
11
Task/Gray-code/D/gray-code-3.d
Normal file
11
Task/Gray-code/D/gray-code-3.d
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import std.stdio, std.algorithm, std.range;
|
||||
|
||||
string[] g(in uint n) pure nothrow {
|
||||
return n ? g(n - 1).map!q{'0' ~ a}.array ~
|
||||
g(n - 1).retro.map!q{'1' ~ a}.array
|
||||
: [""];
|
||||
}
|
||||
|
||||
void main() {
|
||||
4.g.writeln;
|
||||
}
|
||||
23
Task/Gray-code/DWScript/gray-code.dw
Normal file
23
Task/Gray-code/DWScript/gray-code.dw
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
function Encode(v : Integer) : Integer;
|
||||
begin
|
||||
Result := v xor (v shr 1);
|
||||
end;
|
||||
|
||||
function Decode(v : Integer) : Integer;
|
||||
begin
|
||||
Result := 0;
|
||||
while v>0 do begin
|
||||
Result := Result xor v;
|
||||
v := v shr 1;
|
||||
end;
|
||||
end;
|
||||
|
||||
PrintLn('decimal binary gray decoded');
|
||||
|
||||
var i : Integer;
|
||||
for i:=0 to 31 do begin
|
||||
var g := Encode(i);
|
||||
var d := Decode(g);
|
||||
PrintLn(Format(' %2d %s %s %s %2d',
|
||||
[i, IntToBin(i, 5), IntToBin(g, 5), IntToBin(d, 5), d]));
|
||||
end;
|
||||
45
Task/Gray-code/Delphi/gray-code.delphi
Normal file
45
Task/Gray-code/Delphi/gray-code.delphi
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
program GrayCode;
|
||||
|
||||
{$APPTYPE CONSOLE}
|
||||
|
||||
uses SysUtils;
|
||||
|
||||
function Encode(v: Integer): Integer;
|
||||
begin
|
||||
Result := v xor (v shr 1);
|
||||
end;
|
||||
|
||||
function Decode(v: Integer): Integer;
|
||||
begin
|
||||
Result := 0;
|
||||
while v > 0 do
|
||||
begin
|
||||
Result := Result xor v;
|
||||
v := v shr 1;
|
||||
end;
|
||||
end;
|
||||
|
||||
function IntToBin(aValue: LongInt; aDigits: Integer): string;
|
||||
begin
|
||||
Result := StringOfChar('0', aDigits);
|
||||
while aValue > 0 do
|
||||
begin
|
||||
if (aValue and 1) = 1 then
|
||||
Result[aDigits] := '1';
|
||||
Dec(aDigits);
|
||||
aValue := aValue shr 1;
|
||||
end;
|
||||
end;
|
||||
|
||||
var
|
||||
i, g, d: Integer;
|
||||
begin
|
||||
Writeln('decimal binary gray decoded');
|
||||
|
||||
for i := 0 to 31 do
|
||||
begin
|
||||
g := Encode(i);
|
||||
d := Decode(g);
|
||||
Writeln(Format(' %2d %s %s %s %2d', [i, IntToBin(i, 5), IntToBin(g, 5), IntToBin(d, 5), d]));
|
||||
end;
|
||||
end.
|
||||
28
Task/Gray-code/Draco/gray-code.draco
Normal file
28
Task/Gray-code/Draco/gray-code.draco
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
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
|
||||
98
Task/Gray-code/EDSAC-order-code/gray-code.edsac
Normal file
98
Task/Gray-code/EDSAC-order-code/gray-code.edsac
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
[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]
|
||||
15
Task/Gray-code/Elixir/gray-code.elixir
Normal file
15
Task/Gray-code/Elixir/gray-code.elixir
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
defmodule Gray_code do
|
||||
use Bitwise
|
||||
def encode(n), do: bxor(n, bsr(n,1))
|
||||
|
||||
def decode(g), do: decode(g,0)
|
||||
|
||||
def decode(0,n), do: n
|
||||
def decode(g,n), do: decode(bsr(g,1), bxor(g,n))
|
||||
end
|
||||
|
||||
Enum.each(0..31, fn(n) ->
|
||||
g = Gray_code.encode(n)
|
||||
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)
|
||||
9
Task/Gray-code/Erlang/gray-code-1.erl
Normal file
9
Task/Gray-code/Erlang/gray-code-1.erl
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
-module(gray).
|
||||
-export([encode/1, decode/1]).
|
||||
|
||||
encode(N) -> N bxor (N bsr 1).
|
||||
|
||||
decode(G) -> decode(G,0).
|
||||
|
||||
decode(0,N) -> N;
|
||||
decode(G,N) -> decode(G bsr 1, G bxor N).
|
||||
11
Task/Gray-code/Erlang/gray-code-2.erl
Normal file
11
Task/Gray-code/Erlang/gray-code-2.erl
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
-module(testgray).
|
||||
|
||||
test_encode(N) ->
|
||||
G = gray:encode(N),
|
||||
D = gray:decode(G),
|
||||
io:fwrite("~2B : ~5.2.0B : ~5.2.0B : ~5.2.0B : ~2B~n", [N, N, G, D, D]).
|
||||
|
||||
test_encode(N, N) -> [];
|
||||
test_encode(I, N) when I < N -> test_encode(I), test_encode(I+1, N).
|
||||
|
||||
main(_) -> test_encode(0,32).
|
||||
34
Task/Gray-code/Euphoria/gray-code.euphoria
Normal file
34
Task/Gray-code/Euphoria/gray-code.euphoria
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
function gray_encode(integer n)
|
||||
return xor_bits(n,floor(n/2))
|
||||
end function
|
||||
|
||||
function gray_decode(integer n)
|
||||
integer g
|
||||
g = 0
|
||||
while n > 0 do
|
||||
g = xor_bits(g,n)
|
||||
n = floor(n/2)
|
||||
end while
|
||||
return g
|
||||
end function
|
||||
|
||||
function dcb(integer n)
|
||||
atom d,m
|
||||
d = 0
|
||||
m = 1
|
||||
while n do
|
||||
d += remainder(n,2)*m
|
||||
n = floor(n/2)
|
||||
m *= 10
|
||||
end while
|
||||
return d
|
||||
end function
|
||||
|
||||
integer j
|
||||
for i = #0 to #1F do
|
||||
printf(1,"%05d => ",dcb(i))
|
||||
j = gray_encode(i)
|
||||
printf(1,"%05d => ",dcb(j))
|
||||
j = gray_decode(j)
|
||||
printf(1,"%05d\n",dcb(j))
|
||||
end for
|
||||
2
Task/Gray-code/F-Sharp/gray-code-1.fs
Normal file
2
Task/Gray-code/F-Sharp/gray-code-1.fs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
// 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))
|
||||
1
Task/Gray-code/F-Sharp/gray-code-2.fs
Normal file
1
Task/Gray-code/F-Sharp/gray-code-2.fs
Normal file
|
|
@ -0,0 +1 @@
|
|||
[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))
|
||||
16
Task/Gray-code/Factor/gray-code-1.factor
Normal file
16
Task/Gray-code/Factor/gray-code-1.factor
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
USING: math.ranges locals ;
|
||||
IN: rosetta-gray
|
||||
|
||||
: gray-encode ( n -- n' ) dup -1 shift bitxor ;
|
||||
|
||||
:: gray-decode ( n! -- n' )
|
||||
n :> p!
|
||||
[ n -1 shift dup n! 0 = not ] [
|
||||
p n bitxor p!
|
||||
] while
|
||||
p ;
|
||||
|
||||
: main ( -- )
|
||||
-1 32 [a,b] [ dup [ >bin ] [ gray-encode ] bi [ >bin ] [ gray-decode ] bi 4array . ] each ;
|
||||
|
||||
MAIN: main
|
||||
34
Task/Gray-code/Factor/gray-code-2.factor
Normal file
34
Task/Gray-code/Factor/gray-code-2.factor
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
{ -1 "-1" "0" 0 }
|
||||
{ 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 }
|
||||
{ 32 "100000" "110000" 32 }
|
||||
21
Task/Gray-code/Forth/gray-code.fth
Normal file
21
Task/Gray-code/Forth/gray-code.fth
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
: >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 )
|
||||
0 1 31 lshift ( -- g b mask )
|
||||
begin
|
||||
>r \ save a copy of mask on return stack
|
||||
2dup 2/ xor
|
||||
r@ and or
|
||||
r> 1 rshift
|
||||
dup 0=
|
||||
until
|
||||
drop nip ; \ clean the parameter stack leaving result only
|
||||
|
||||
: test
|
||||
2 base ! \ set system number base to 2. ie: Binary
|
||||
32 0 do
|
||||
cr I dup 5 .r ." ==> " \ print numbers (binary) right justified 5 places
|
||||
>gray dup 5 .r ." ==> "
|
||||
gray> 5 .r
|
||||
loop
|
||||
decimal ; \ revert to BASE 10
|
||||
46
Task/Gray-code/Fortran/gray-code.f
Normal file
46
Task/Gray-code/Fortran/gray-code.f
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
PROGRAM GRAY
|
||||
IMPLICIT NONE
|
||||
INTEGER IGRAY,I,J,K
|
||||
CHARACTER*5 A,B,C
|
||||
DO 10 I=0,31
|
||||
J=IGRAY(I,1)
|
||||
K=IGRAY(J,-1)
|
||||
CALL BINARY(A,I,5)
|
||||
CALL BINARY(B,J,5)
|
||||
CALL BINARY(C,K,5)
|
||||
PRINT 99,I,A,B,C,K
|
||||
10 CONTINUE
|
||||
99 FORMAT(I2,3H : ,A5,4H => ,A5,4H => ,A5,3H : ,I2)
|
||||
END
|
||||
|
||||
FUNCTION IGRAY(N,D)
|
||||
IMPLICIT NONE
|
||||
INTEGER D,K,N,IGRAY
|
||||
IF(D.LT.0) GO TO 10
|
||||
IGRAY=IEOR(N,ISHFT(N,-1))
|
||||
RETURN
|
||||
10 K=N
|
||||
IGRAY=0
|
||||
20 IGRAY=IEOR(IGRAY,K)
|
||||
K=K/2
|
||||
IF(K.NE.0) GO TO 20
|
||||
END
|
||||
|
||||
SUBROUTINE BINARY(S,N,K)
|
||||
IMPLICIT NONE
|
||||
INTEGER I,K,L,N
|
||||
CHARACTER*(*) S
|
||||
L=LEN(S)
|
||||
DO 10 I=0,K-1
|
||||
C The following line may replace the next block-if,
|
||||
C on machines using ASCII code :
|
||||
C S(L-I:L-I)=CHAR(48+IAND(1,ISHFT(N,-I)))
|
||||
C On EBCDIC machines, use 240 instead of 48.
|
||||
IF(BTEST(N,I)) THEN
|
||||
S(L-I:L-I)='1'
|
||||
ELSE
|
||||
S(L-I:L-I)='0'
|
||||
END IF
|
||||
10 CONTINUE
|
||||
S(1:L-K)=''
|
||||
END
|
||||
41
Task/Gray-code/FreeBASIC/gray-code.basic
Normal file
41
Task/Gray-code/FreeBASIC/gray-code.basic
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
' 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
|
||||
6
Task/Gray-code/Frink/gray-code.frink
Normal file
6
Task/Gray-code/Frink/gray-code.frink
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
for i=0 to 31
|
||||
{
|
||||
gray = binaryToGray[i]
|
||||
back = grayToBinary[gray]
|
||||
println[(i->binary) + "\t" + (gray->binary) + "\t" + (back->binary)]
|
||||
}
|
||||
23
Task/Gray-code/Go/gray-code.go
Normal file
23
Task/Gray-code/Go/gray-code.go
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func enc(b int) int {
|
||||
return b ^ b>>1
|
||||
}
|
||||
|
||||
func dec(g int) (b int) {
|
||||
for ; g != 0; g >>= 1 {
|
||||
b ^= g
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("decimal binary gray decoded")
|
||||
for b := 0; b < 32; b++ {
|
||||
g := enc(b)
|
||||
d := dec(g)
|
||||
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
|
||||
}
|
||||
}
|
||||
10
Task/Gray-code/Groovy/gray-code-1.groovy
Normal file
10
Task/Gray-code/Groovy/gray-code-1.groovy
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
def grayEncode = { i ->
|
||||
i ^ (i >>> 1)
|
||||
}
|
||||
|
||||
def grayDecode;
|
||||
grayDecode = { int code ->
|
||||
if(code <= 0) return 0
|
||||
def h = grayDecode(code >>> 1)
|
||||
return (h << 1) + ((code ^ h) & 1)
|
||||
}
|
||||
21
Task/Gray-code/Groovy/gray-code-2.groovy
Normal file
21
Task/Gray-code/Groovy/gray-code-2.groovy
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
def binary = { i, minBits = 1 ->
|
||||
def remainder = i
|
||||
def bin = []
|
||||
while (remainder > 0 || bin.size() <= minBits) {
|
||||
bin << (remainder & 1)
|
||||
remainder >>>= 1
|
||||
}
|
||||
bin
|
||||
}
|
||||
|
||||
println "number binary gray code decode"
|
||||
println "====== ====== ========= ======"
|
||||
(0..31).each {
|
||||
def code = grayEncode(it)
|
||||
def decode = grayDecode(code)
|
||||
def iB = binary(it, 5)
|
||||
def cB = binary(code, 5)
|
||||
printf(" %2d %1d%1d%1d%1d%1d %1d%1d%1d%1d%1d %2d",
|
||||
it, iB[4],iB[3],iB[2],iB[1],iB[0], cB[4],cB[3],cB[2],cB[1],cB[0], decode)
|
||||
println()
|
||||
}
|
||||
23
Task/Gray-code/Haskell/gray-code.hs
Normal file
23
Task/Gray-code/Haskell/gray-code.hs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import Data.Bits
|
||||
import Data.Char
|
||||
import Numeric
|
||||
import Control.Monad
|
||||
import Text.Printf
|
||||
|
||||
grayToBin :: (Integral t, Bits t) => t -> t
|
||||
grayToBin 0 = 0
|
||||
grayToBin g = g `xor` (grayToBin $ g `shiftR` 1)
|
||||
|
||||
binToGray :: (Integral t, Bits t) => t -> t
|
||||
binToGray b = b `xor` (b `shiftR` 1)
|
||||
|
||||
showBinary :: (Integral t, Show t) => t -> String
|
||||
showBinary n = showIntAtBase 2 intToDigit n ""
|
||||
|
||||
showGrayCode :: (Integral t, Bits t, PrintfArg t, Show t) => t -> IO ()
|
||||
showGrayCode num = do
|
||||
let bin = showBinary num
|
||||
let gray = showBinary (binToGray num)
|
||||
printf "int: %2d -> bin: %5s -> gray: %5s\n" num bin gray
|
||||
|
||||
main = forM_ [0..31::Int] showGrayCode
|
||||
18
Task/Gray-code/Icon/gray-code.icon
Normal file
18
Task/Gray-code/Icon/gray-code.icon
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
link bitint
|
||||
|
||||
procedure main()
|
||||
every write(right(i := 0 to 10,4),":",right(int2bit(i),10)," -> ",
|
||||
right(g := gEncode(i),10)," -> ",
|
||||
right(b := gDecode(g),10)," -> ",
|
||||
right(bit2int(b),10))
|
||||
end
|
||||
|
||||
procedure gEncode(b)
|
||||
return int2bit(ixor(b, ishift(b,-1)))
|
||||
end
|
||||
|
||||
procedure gDecode(g)
|
||||
b := g[1]
|
||||
every i := 2 to *g do b ||:= if g[i] == b[i-1] then "0" else "1"
|
||||
return b
|
||||
end
|
||||
1
Task/Gray-code/J/gray-code-1.j
Normal file
1
Task/Gray-code/J/gray-code-1.j
Normal file
|
|
@ -0,0 +1 @@
|
|||
G2B=: ~:/\&.|:
|
||||
39
Task/Gray-code/J/gray-code-2.j
Normal file
39
Task/Gray-code/J/gray-code-2.j
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
n=:i.32
|
||||
G2B=: ~:/\&.|:
|
||||
(,: ,.@".&.>) 'n';'#:n';'G2B inv#:n';'#.G2B G2B inv#:n'
|
||||
+--+---------+----------+----------------+
|
||||
|n |#:n |G2B inv#:n|#.G2B G2B inv#:n|
|
||||
+--+---------+----------+----------------+
|
||||
| 0|0 0 0 0 0|0 0 0 0 0 | 0 |
|
||||
| 1|0 0 0 0 1|0 0 0 0 1 | 1 |
|
||||
| 2|0 0 0 1 0|0 0 0 1 1 | 2 |
|
||||
| 3|0 0 0 1 1|0 0 0 1 0 | 3 |
|
||||
| 4|0 0 1 0 0|0 0 1 1 0 | 4 |
|
||||
| 5|0 0 1 0 1|0 0 1 1 1 | 5 |
|
||||
| 6|0 0 1 1 0|0 0 1 0 1 | 6 |
|
||||
| 7|0 0 1 1 1|0 0 1 0 0 | 7 |
|
||||
| 8|0 1 0 0 0|0 1 1 0 0 | 8 |
|
||||
| 9|0 1 0 0 1|0 1 1 0 1 | 9 |
|
||||
|10|0 1 0 1 0|0 1 1 1 1 |10 |
|
||||
|11|0 1 0 1 1|0 1 1 1 0 |11 |
|
||||
|12|0 1 1 0 0|0 1 0 1 0 |12 |
|
||||
|13|0 1 1 0 1|0 1 0 1 1 |13 |
|
||||
|14|0 1 1 1 0|0 1 0 0 1 |14 |
|
||||
|15|0 1 1 1 1|0 1 0 0 0 |15 |
|
||||
|16|1 0 0 0 0|1 1 0 0 0 |16 |
|
||||
|17|1 0 0 0 1|1 1 0 0 1 |17 |
|
||||
|18|1 0 0 1 0|1 1 0 1 1 |18 |
|
||||
|19|1 0 0 1 1|1 1 0 1 0 |19 |
|
||||
|20|1 0 1 0 0|1 1 1 1 0 |20 |
|
||||
|21|1 0 1 0 1|1 1 1 1 1 |21 |
|
||||
|22|1 0 1 1 0|1 1 1 0 1 |22 |
|
||||
|23|1 0 1 1 1|1 1 1 0 0 |23 |
|
||||
|24|1 1 0 0 0|1 0 1 0 0 |24 |
|
||||
|25|1 1 0 0 1|1 0 1 0 1 |25 |
|
||||
|26|1 1 0 1 0|1 0 1 1 1 |26 |
|
||||
|27|1 1 0 1 1|1 0 1 1 0 |27 |
|
||||
|28|1 1 1 0 0|1 0 0 1 0 |28 |
|
||||
|29|1 1 1 0 1|1 0 0 1 1 |29 |
|
||||
|30|1 1 1 1 0|1 0 0 0 1 |30 |
|
||||
|31|1 1 1 1 1|1 0 0 0 0 |31 |
|
||||
+--+---------+----------+----------------+
|
||||
85
Task/Gray-code/Java/gray-code.java
Normal file
85
Task/Gray-code/Java/gray-code.java
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
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 = 0; i < 32; i++ ) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
13
Task/Gray-code/JavaScript/gray-code-1.js
Normal file
13
Task/Gray-code/JavaScript/gray-code-1.js
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
export function encode (number) {
|
||||
return number ^ (number >> 1)
|
||||
}
|
||||
|
||||
export function decode (encodedNumber) {
|
||||
let number = encodedNumber
|
||||
|
||||
while (encodedNumber >>= 1) {
|
||||
number ^= encodedNumber
|
||||
}
|
||||
|
||||
return number
|
||||
}
|
||||
22
Task/Gray-code/JavaScript/gray-code-2.js
Normal file
22
Task/Gray-code/JavaScript/gray-code-2.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import printf from 'printf' // Module must be installed with npm first
|
||||
import * as gray from './gray-code.js'
|
||||
|
||||
console.log(
|
||||
'Number\t' +
|
||||
'Binary\t' +
|
||||
'Gray Code\t' +
|
||||
'Decoded Gray Code'
|
||||
)
|
||||
|
||||
for (let number = 0; number < 32; number++) {
|
||||
const grayCode = gray.encode(number)
|
||||
const decodedGrayCode = gray.decode(grayCode)
|
||||
|
||||
console.log(printf(
|
||||
'%2d\t%05d\t%05d\t\t%2d',
|
||||
number,
|
||||
number.toString(2),
|
||||
grayCode.toString(2),
|
||||
decodedGrayCode
|
||||
))
|
||||
}
|
||||
8
Task/Gray-code/Julia/gray-code.julia
Normal file
8
Task/Gray-code/Julia/gray-code.julia
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
grayencode(n::Integer) = n ⊻ (n >> 1)
|
||||
function graydecode(n::Integer)
|
||||
r = n
|
||||
while (n >>= 1) != 0
|
||||
r ⊻= n
|
||||
end
|
||||
return r
|
||||
end
|
||||
8
Task/Gray-code/K/gray-code-1.k
Normal file
8
Task/Gray-code/K/gray-code-1.k
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
xor: {~x=y}
|
||||
gray:{x[0],xor':x}
|
||||
|
||||
/ variant: using shift
|
||||
gray1:{(x[0],xor[1_ x;-1_ x])}
|
||||
|
||||
/ variant: iterative
|
||||
gray2:{x[0],{:[x[y-1]=1;~x[y];x[y]]}[x]'1+!(#x)-1}
|
||||
1
Task/Gray-code/K/gray-code-2.k
Normal file
1
Task/Gray-code/K/gray-code-2.k
Normal file
|
|
@ -0,0 +1 @@
|
|||
g2b:xor\
|
||||
9
Task/Gray-code/K/gray-code-3.k
Normal file
9
Task/Gray-code/K/gray-code-3.k
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
gray\1 0 0 0 0
|
||||
(1 0 0 0 0
|
||||
1 1 0 0 0
|
||||
1 0 1 0 0
|
||||
1 1 1 1 0
|
||||
1 0 0 0 1
|
||||
1 1 0 0 1
|
||||
1 0 1 0 1
|
||||
1 1 1 1 1)
|
||||
1
Task/Gray-code/K/gray-code-4.k
Normal file
1
Task/Gray-code/K/gray-code-4.k
Normal file
|
|
@ -0,0 +1 @@
|
|||
g2b1:*|{gray x}\
|
||||
1
Task/Gray-code/K/gray-code-5.k
Normal file
1
Task/Gray-code/K/gray-code-5.k
Normal file
|
|
@ -0,0 +1 @@
|
|||
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}
|
||||
7
Task/Gray-code/K/gray-code-6.k
Normal file
7
Task/Gray-code/K/gray-code-6.k
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
gray:{x[0],xor':x}
|
||||
g2b:xor\
|
||||
/ using allcomb instead of 2_vs'!32 for nicer presentation
|
||||
allcomb:{+(x#y)_vs!_ y^x}
|
||||
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
|
||||
24
Task/Gray-code/Kotlin/gray-code.kotlin
Normal file
24
Task/Gray-code/Kotlin/gray-code.kotlin
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
// version 1.0.6
|
||||
|
||||
object Gray {
|
||||
fun encode(n: Int) = n xor (n shr 1)
|
||||
|
||||
fun decode(n: Int): Int {
|
||||
var p = n
|
||||
var nn = n
|
||||
while (nn != 0) {
|
||||
nn = nn shr 1
|
||||
p = p xor nn
|
||||
}
|
||||
return p
|
||||
}
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
println("Number\tBinary\tGray\tDecoded")
|
||||
for (i in 0..31) {
|
||||
print("$i\t${Integer.toBinaryString(i)}\t")
|
||||
val g = Gray.encode(i)
|
||||
println("${Integer.toBinaryString(g)}\t${Gray.decode(g)}")
|
||||
}
|
||||
}
|
||||
55
Task/Gray-code/Liberty-BASIC/gray-code.basic
Normal file
55
Task/Gray-code/Liberty-BASIC/gray-code.basic
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
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
|
||||
50
Task/Gray-code/Limbo/gray-code.limbo
Normal file
50
Task/Gray-code/Limbo/gray-code.limbo
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
implement Gray;
|
||||
|
||||
include "sys.m"; sys: Sys;
|
||||
print: import sys;
|
||||
include "draw.m";
|
||||
|
||||
Gray: module {
|
||||
init: fn(nil: ref Draw->Context, args: list of string);
|
||||
# Export gray and grayinv so that this module can be used as either a
|
||||
# standalone program or as a library:
|
||||
gray: fn(n: int): int;
|
||||
grayinv: fn(n: int): int;
|
||||
};
|
||||
|
||||
init(nil: ref Draw->Context, args: list of string)
|
||||
{
|
||||
sys = load Sys Sys->PATH;
|
||||
for(i := 0; i < 32; i++) {
|
||||
g := gray(i);
|
||||
f := grayinv(g);
|
||||
print("%2d %5s %2d %5s %5s %2d\n", i, binstr(i), g, binstr(g), binstr(f), f);
|
||||
}
|
||||
}
|
||||
|
||||
gray(n: int): int
|
||||
{
|
||||
return n ^ (n >> 1);
|
||||
}
|
||||
|
||||
grayinv(n: int): int
|
||||
{
|
||||
r := 0;
|
||||
while(n) {
|
||||
r ^= n;
|
||||
n >>= 1;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
binstr(n: int): string
|
||||
{
|
||||
if(!n)
|
||||
return "0";
|
||||
s := "";
|
||||
while(n) {
|
||||
s = (string (n&1)) + s;
|
||||
n >>= 1;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
19
Task/Gray-code/Lobster/gray-code.lobster
Normal file
19
Task/Gray-code/Lobster/gray-code.lobster
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
def grey_encode(n) -> int:
|
||||
return n ^ (n >> 1)
|
||||
|
||||
def grey_decode(n) -> int:
|
||||
var p = n
|
||||
n = n >> 1
|
||||
while n != 0:
|
||||
p = p ^ n
|
||||
n = n >> 1
|
||||
return p
|
||||
|
||||
for(32) i:
|
||||
let g = grey_encode(i)
|
||||
let b = grey_decode(g)
|
||||
print(number_to_string(i, 10, 2) + " : " +
|
||||
number_to_string(i, 2, 5) + " ⇾ " +
|
||||
number_to_string(g, 2, 5) + " ⇾ " +
|
||||
number_to_string(b, 2, 5) + " : " +
|
||||
number_to_string(b, 10, 2))
|
||||
13
Task/Gray-code/Logo/gray-code-1.logo
Normal file
13
Task/Gray-code/Logo/gray-code-1.logo
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
to gray_encode :number
|
||||
output bitxor :number lshift :number -1
|
||||
end
|
||||
|
||||
to gray_decode :code
|
||||
local "value
|
||||
make "value 0
|
||||
while [:code > 0] [
|
||||
make "value bitxor :code :value
|
||||
make "code lshift :code -1
|
||||
]
|
||||
output :value
|
||||
end
|
||||
29
Task/Gray-code/Logo/gray-code-2.logo
Normal file
29
Task/Gray-code/Logo/gray-code-2.logo
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
to format :str :width [pad (char 32)]
|
||||
while [(count :str) < :width] [
|
||||
make "str word :pad :str
|
||||
]
|
||||
output :str
|
||||
end
|
||||
|
||||
; Output binary representation of a number
|
||||
to binary :number [:width 1]
|
||||
local "bits
|
||||
ifelse [:number = 0] [
|
||||
make "bits 0
|
||||
] [
|
||||
make "bits "
|
||||
while [:number > 0] [
|
||||
make "bits word (bitand :number 1) :bits
|
||||
make "number lshift :number -1
|
||||
]
|
||||
]
|
||||
output (format :bits :width 0)
|
||||
end
|
||||
|
||||
repeat 32 [
|
||||
make "num repcount - 1
|
||||
make "gray gray_encode :num
|
||||
make "decoded gray_decode :gray
|
||||
print (sentence (format :num 2) ": (binary :num 5) ": (binary :gray 5) ":
|
||||
(binary :decoded 5) ": (format :decoded 2)) ]
|
||||
bye
|
||||
18
Task/Gray-code/Lua/gray-code-1.lua
Normal file
18
Task/Gray-code/Lua/gray-code-1.lua
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
local _M = {}
|
||||
|
||||
local bit = require('bit')
|
||||
local math = require('math')
|
||||
|
||||
_M.encode = function(number)
|
||||
return bit.bxor(number, bit.rshift(number, 1));
|
||||
end
|
||||
|
||||
_M.decode = function(gray_code)
|
||||
local value = 0
|
||||
while gray_code > 0 do
|
||||
gray_code, value = bit.rshift(gray_code, 1), bit.bxor(gray_code, value)
|
||||
end
|
||||
return value
|
||||
end
|
||||
|
||||
return _M
|
||||
24
Task/Gray-code/Lua/gray-code-2.lua
Normal file
24
Task/Gray-code/Lua/gray-code-2.lua
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
local bit = require 'bit'
|
||||
local gray = require 'gray'
|
||||
|
||||
-- simple binary string formatter
|
||||
local function to_bit_string(n, width)
|
||||
width = width or 1
|
||||
local output = ""
|
||||
while n > 0 do
|
||||
output = bit.band(n,1) .. output
|
||||
n = bit.rshift(n,1)
|
||||
end
|
||||
while #output < width do
|
||||
output = '0' .. output
|
||||
end
|
||||
return output
|
||||
end
|
||||
|
||||
for i = 0,31 do
|
||||
g = gray.encode(i);
|
||||
gd = gray.decode(g);
|
||||
print(string.format("%2d : %s => %s => %s : %2d", i,
|
||||
to_bit_string(i,5), to_bit_string(g, 5),
|
||||
to_bit_string(gd,5), gd))
|
||||
end
|
||||
29
Task/Gray-code/M2000-Interpreter/gray-code.m2000
Normal file
29
Task/Gray-code/M2000-Interpreter/gray-code.m2000
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
Module Code32 (&code(), &decode()){
|
||||
Const d$="{0::-2} {1:-6} {2:-6} {3:-6} {4::-2}"
|
||||
For i=0 to 32
|
||||
g=code(i)
|
||||
b=decode(g)
|
||||
Print format$(d$, i, @bin$(i), @bin$(g), @bin$(b), b)
|
||||
Next
|
||||
// static function
|
||||
Function bin$(a)
|
||||
a$=""
|
||||
Do n= a mod 2 : a$=if$(n=1->"1", "0")+a$ : a|div 2 : Until a==0
|
||||
=a$
|
||||
End Function
|
||||
}
|
||||
Module GrayCode {
|
||||
Module doit (&a(), &b()) { }
|
||||
Function GrayEncode(a) {
|
||||
=binary.xor(a, binary.shift(a,-1))
|
||||
}
|
||||
Function GrayDecode(a) {
|
||||
b=0
|
||||
Do b=binary.xor(a, b) : a=binary.shift(a,-1) : Until a==0
|
||||
=b
|
||||
}
|
||||
// pass 2 functions to Code32
|
||||
doit &GrayEncode(), &GrayDecode()
|
||||
}
|
||||
// pass Code32 to GrayCode in place of doit
|
||||
GrayCode ; doit as Code32
|
||||
43
Task/Gray-code/MATLAB/gray-code.m
Normal file
43
Task/Gray-code/MATLAB/gray-code.m
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
%% Gray Code Generator
|
||||
% this script generates gray codes of n bits
|
||||
% total 2^n -1 continuous gray codes will be generated.
|
||||
% this code follows a recursive approach. therefore,
|
||||
% it can be slow for large n
|
||||
|
||||
|
||||
|
||||
clear all;
|
||||
clc;
|
||||
|
||||
bits = input('Enter the number of bits: ');
|
||||
if (bits<1)
|
||||
disp('Sorry, number of bits should be positive');
|
||||
elseif (mod(bits,1)~=0)
|
||||
disp('Sorry, number of bits can only be positive integers');
|
||||
else
|
||||
initial_container = [0;1];
|
||||
if bits == 1
|
||||
result = initial_container;
|
||||
else
|
||||
previous_container = initial_container;
|
||||
for i=2:bits
|
||||
new_gray_container = zeros(2^i,i);
|
||||
new_gray_container(1:(2^i)/2,1) = 0;
|
||||
new_gray_container(((2^i)/2)+1:end,1) = 1;
|
||||
|
||||
for j = 1:(2^i)/2
|
||||
new_gray_container(j,2:end) = previous_container(j,:);
|
||||
end
|
||||
|
||||
for j = ((2^i)/2)+1:2^i
|
||||
new_gray_container(j,2:end) = previous_container((2^i)+1-j,:);
|
||||
end
|
||||
|
||||
previous_container = new_gray_container;
|
||||
end
|
||||
result = previous_container;
|
||||
end
|
||||
fprintf('Gray code of %d bits',bits);
|
||||
disp(' ');
|
||||
disp(result);
|
||||
end
|
||||
2
Task/Gray-code/Mathematica/gray-code.math
Normal file
2
Task/Gray-code/Mathematica/gray-code.math
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
graycode[n_]:=BitXor[n,BitShiftRight[n]]
|
||||
graydecode[n_]:=Fold[BitXor,0,FixedPointList[BitShiftRight,n]]
|
||||
30
Task/Gray-code/Mercury/gray-code-1.mercury
Normal file
30
Task/Gray-code/Mercury/gray-code-1.mercury
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
:- module gray.
|
||||
|
||||
:- interface.
|
||||
:- import_module int.
|
||||
|
||||
:- type gray.
|
||||
|
||||
% VALUE conversion functions
|
||||
:- func gray.from_int(int) = gray.
|
||||
:- func gray.to_int(gray) = int.
|
||||
|
||||
% REPRESENTATION conversion predicate
|
||||
:- pred gray.coerce(gray, int).
|
||||
:- mode gray.coerce(in, out) is det.
|
||||
:- mode gray.coerce(out, in) is det.
|
||||
|
||||
:- implementation.
|
||||
|
||||
:- import_module list.
|
||||
|
||||
:- type gray
|
||||
---> gray(int).
|
||||
|
||||
gray.from_int(X) = gray(X `xor` (X >> 1)).
|
||||
|
||||
gray.to_int(gray(G)) = (G > 0 -> G `xor` gray.to_int(gray(G >> 1))
|
||||
; G).
|
||||
gray.coerce(gray(I), I).
|
||||
|
||||
:- end_module gray.
|
||||
40
Task/Gray-code/Mercury/gray-code-2.mercury
Normal file
40
Task/Gray-code/Mercury/gray-code-2.mercury
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
:- module gray_test.
|
||||
|
||||
:- interface.
|
||||
|
||||
:- import_module io.
|
||||
|
||||
:- pred main(io::di, io::uo) is det.
|
||||
|
||||
:- implementation.
|
||||
|
||||
:- import_module gray.
|
||||
:- import_module int, list, string.
|
||||
|
||||
:- pred check_conversion(list(int)::in, list(gray)::out) is semidet.
|
||||
:- pred display_lists(list(int)::in, list(gray)::in, io::di, io::uo) is det.
|
||||
:- pred display_record(int::in, gray::in, io::di, io::uo) is det.
|
||||
|
||||
main(!IO) :-
|
||||
Numbers = 0..31,
|
||||
( check_conversion(Numbers, Grays) ->
|
||||
io.format("%8s %8s %8s\n", [s("Number"), s("Binary"), s("Gray")], !IO),
|
||||
io.format("%8s %8s %8s\n", [s("------"), s("------"), s("----")], !IO),
|
||||
display_lists(Numbers, Grays, !IO)
|
||||
|
||||
; io.write("Either conversion or back-conversion failed.\n", !IO)).
|
||||
|
||||
check_conversion(Numbers, Grays) :-
|
||||
Grays = list.map(gray.from_int, Numbers),
|
||||
Numbers = list.map(gray.to_int, Grays).
|
||||
|
||||
display_lists(Numbers, Grays, !IO) :-
|
||||
list.foldl_corresponding(display_record, Numbers, Grays, !IO).
|
||||
|
||||
display_record(Number, Gray, !IO) :-
|
||||
gray.coerce(Gray, GrayRep),
|
||||
NumBin = string.int_to_base_string(Number, 2),
|
||||
GrayBin = string.int_to_base_string(GrayRep, 2),
|
||||
io.format("%8d %8s %8s\n", [i(Number), s(NumBin), s(GrayBin)], !IO).
|
||||
|
||||
:- end_module gray_test.
|
||||
64
Task/Gray-code/NOWUT/gray-code.nowut
Normal file
64
Task/Gray-code/NOWUT/gray-code.nowut
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
; link with PIOxxx.OBJ
|
||||
|
||||
sectiondata
|
||||
|
||||
output: db " : "
|
||||
inbinary: db "00000 => "
|
||||
graybinary: db "00000 => "
|
||||
outbinary: db "00000"
|
||||
db 13,10,0 ; carriage return and null terminator
|
||||
|
||||
sectioncode
|
||||
|
||||
start!
|
||||
gosub initplatform
|
||||
|
||||
beginfunc
|
||||
localvar i.d,g.d,b.d
|
||||
|
||||
i=0
|
||||
whileless i,32
|
||||
callex g,gray_encode,i
|
||||
callex b,gray_decode,g
|
||||
|
||||
callex ,bin2string,i,inbinary,5 ; 5 = number of binary digits
|
||||
callex ,bin2string,g,graybinary,5
|
||||
callex ,bin2string,b,outbinary,5
|
||||
|
||||
callex ,printhex8,i ; display hex value
|
||||
; because there is no PIO routine for decimals...
|
||||
callex ,printnt,output.a
|
||||
|
||||
i=_+1
|
||||
wend
|
||||
|
||||
endfunc
|
||||
end
|
||||
|
||||
gray_encode:
|
||||
beginfunc n.d
|
||||
n=_ xor (n shr 1)
|
||||
endfunc n
|
||||
returnex 4 ; clean off 1 parameter from the stack
|
||||
|
||||
gray_decode:
|
||||
beginfunc n.d
|
||||
localvar p.d
|
||||
p=n
|
||||
whilegreater n,1
|
||||
n=_ shr 1 > p=_ xor n
|
||||
wend
|
||||
endfunc p
|
||||
returnex 4 ; clean off 1 parameter from the stack
|
||||
|
||||
bin2string:
|
||||
beginfunc digits.d,straddr.d,value.d
|
||||
|
||||
whilegreater digits,0
|
||||
digits=_-1
|
||||
[straddr].b=value shr digits and 1+$30 ; write an ASCII '0' or '1'
|
||||
straddr=_+1 ; increment the pointer
|
||||
wend
|
||||
|
||||
endfunc
|
||||
returnex $0C ; clean off 3 parameters from the stack
|
||||
9
Task/Gray-code/Nim/gray-code-1.nim
Normal file
9
Task/Gray-code/Nim/gray-code-1.nim
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
proc grayEncode(n: int): int =
|
||||
n xor (n shr 1)
|
||||
|
||||
proc grayDecode(n: int): int =
|
||||
result = n
|
||||
var t = n
|
||||
while t > 0:
|
||||
t = t shr 1
|
||||
result = result xor t
|
||||
4
Task/Gray-code/Nim/gray-code-2.nim
Normal file
4
Task/Gray-code/Nim/gray-code-2.nim
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import strutils, strformat
|
||||
|
||||
for i in 0 .. 32:
|
||||
echo &"{i:>2} => {toBin(grayEncode(i), 6)} => {grayDecode(grayEncode(i)):>2}"
|
||||
26
Task/Gray-code/OCaml/gray-code.ocaml
Normal file
26
Task/Gray-code/OCaml/gray-code.ocaml
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
let gray_encode b =
|
||||
b lxor (b lsr 1)
|
||||
|
||||
let gray_decode n =
|
||||
let rec aux p n =
|
||||
if n = 0 then p
|
||||
else aux (p lxor n) (n lsr 1)
|
||||
in
|
||||
aux n (n lsr 1)
|
||||
|
||||
let bool_string len n =
|
||||
let s = Bytes.make len '0' in
|
||||
let rec aux i n =
|
||||
if n land 1 = 1 then Bytes.set s i '1';
|
||||
if i <= 0 then (Bytes.to_string s)
|
||||
else aux (pred i) (n lsr 1)
|
||||
in
|
||||
aux (pred len) n
|
||||
|
||||
let () =
|
||||
let s = bool_string 5 in
|
||||
for i = 0 to pred 32 do
|
||||
let g = gray_encode i in
|
||||
let b = gray_decode g in
|
||||
Printf.printf "%2d : %s => %s => %s : %2d\n" i (s i) (s g) (s b) b
|
||||
done
|
||||
5
Task/Gray-code/PARI-GP/gray-code.parigp
Normal file
5
Task/Gray-code/PARI-GP/gray-code.parigp
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
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)))
|
||||
28
Task/Gray-code/PHP/gray-code.php
Normal file
28
Task/Gray-code/PHP/gray-code.php
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @author Elad Yosifon
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param int $binary
|
||||
* @return int
|
||||
*/
|
||||
function gray_encode($binary){
|
||||
return $binary ^ ($binary >> 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $gray
|
||||
* @return int
|
||||
*/
|
||||
function gray_decode($gray){
|
||||
$binary = $gray;
|
||||
while($gray >>= 1) $binary ^= $gray;
|
||||
return $binary;
|
||||
}
|
||||
|
||||
for($i=0;$i<32;$i++){
|
||||
$gray_encoded = gray_encode($i);
|
||||
printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
|
||||
}
|
||||
31
Task/Gray-code/PL-I/gray-code.pli
Normal file
31
Task/Gray-code/PL-I/gray-code.pli
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
(stringrange, stringsize):
|
||||
Gray_code: procedure options (main); /* 15 November 2013 */
|
||||
declare (bin(0:31), g(0:31), b2(0:31)) bit (5);
|
||||
declare (c, carry) bit (1);
|
||||
declare (i, j) fixed binary (7);
|
||||
|
||||
bin(0) = '00000'b;
|
||||
do i = 0 to 31;
|
||||
if i > 0 then
|
||||
do;
|
||||
carry = '1'b;
|
||||
bin(i) = bin(i-1);
|
||||
do j = 5 to 1 by -1;
|
||||
c = substr(bin(i), j, 1) & carry;
|
||||
substr(bin(i), j, 1) = substr(bin(i), j, 1) ^ carry;
|
||||
carry = c;
|
||||
end;
|
||||
end;
|
||||
g(i) = bin(i) ^ '0'b || substr(bin(i), 1, 4);
|
||||
end;
|
||||
do i = 0 to 31;
|
||||
substr(b2(i), 1, 1) = substr(g(i), 1, 1);
|
||||
do j = 2 to 5;
|
||||
substr(b2(i), j, 1) = substr(g(i), j, 1) ^ substr(bin(i), j-1, 1);
|
||||
end;
|
||||
end;
|
||||
|
||||
do i = 0 to 31;
|
||||
put skip edit (i, bin(i), g(i), b2(i)) (f(2), 3(x(1), b));
|
||||
end;
|
||||
end Gray_code;
|
||||
45
Task/Gray-code/PL-M/gray-code.plm
Normal file
45
Task/Gray-code/PL-M/gray-code.plm
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
100H:
|
||||
|
||||
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
|
||||
EXIT: PROCEDURE; GO TO 0; END EXIT;
|
||||
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
|
||||
|
||||
PRINT$NUM: PROCEDURE (N, BASE);
|
||||
DECLARE S (17) BYTE INITIAL ('................$');
|
||||
DECLARE (N, P) ADDRESS, (DGT BASED P, BASE) BYTE;
|
||||
P = .S(16);
|
||||
DIGIT:
|
||||
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
|
||||
20
Task/Gray-code/Perl/gray-code.pl
Normal file
20
Task/Gray-code/Perl/gray-code.pl
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
sub bin2gray
|
||||
{
|
||||
return $_[0] ^ ($_[0] >> 1);
|
||||
}
|
||||
|
||||
sub gray2bin
|
||||
{
|
||||
my ($num)= @_;
|
||||
my $bin= $num;
|
||||
while( $num >>= 1 ) {
|
||||
# a bit ends up flipped iff an odd number of bits to its left is set.
|
||||
$bin ^= $num; # different from the suggested algorithm;
|
||||
} # avoids using bit mask and explicit bittery
|
||||
return $bin;
|
||||
}
|
||||
|
||||
for (0..31) {
|
||||
my $gr= bin2gray($_);
|
||||
printf "%d\t%b\t%b\t%b\n", $_, $_, $gr, gray2bin($gr);
|
||||
}
|
||||
24
Task/Gray-code/Phix/gray-code.phix
Normal file
24
Task/Gray-code/Phix/gray-code.phix
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
(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>
|
||||
<span style="color: #008080;">return</span> <span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
|
||||
|
||||
<span style="color: #008080;">function</span> <span style="color: #000000;">gray_decode</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
|
||||
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
|
||||
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
|
||||
<span style="color: #008080;">return</span> <span style="color: #000000;">r</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
|
||||
|
||||
<span style="color: #004080;">integer</span> <span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span>
|
||||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" N Binary Gray Decoded\n"</span><span style="color: #0000FF;">&</span>
|
||||
<span style="color: #008000;">"== ===== ===== =======\n"</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">31</span> <span style="color: #008080;">do</span>
|
||||
<span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">gray_encode</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">gray_decode</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">)</span>
|
||||
<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>
|
||||
<!--
|
||||
26
Task/Gray-code/Picat/gray-code.picat
Normal file
26
Task/Gray-code/Picat/gray-code.picat
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
go =>
|
||||
foreach(I in 0..2**5-1)
|
||||
G = gray_encode1(I),
|
||||
E = gray_decode1(G),
|
||||
printf("%2d %6w %2d %6w %6w %2d\n",I,I.to_binary_string,
|
||||
G, G.to_binary_string,
|
||||
E.to_binary_string, E)
|
||||
end,
|
||||
nl,
|
||||
println("Checking 2**1300:"),
|
||||
N2=2**1300,
|
||||
G2=gray_encode1(N2),
|
||||
E2=gray_decode1(G2),
|
||||
% println(g2=G2),
|
||||
% println(e2=E2),
|
||||
println(check=cond(N2==E2,same,not_same)),
|
||||
nl.
|
||||
|
||||
gray_encode1(N) = N ^ (N >> 1).
|
||||
gray_decode1(N) = P =>
|
||||
P = N,
|
||||
N := N >> 1,
|
||||
while (N != 0)
|
||||
P := P ^ N,
|
||||
N := N >> 1
|
||||
end.
|
||||
10
Task/Gray-code/PicoLisp/gray-code-1.l
Normal file
10
Task/Gray-code/PicoLisp/gray-code-1.l
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
(de grayEncode (N)
|
||||
(bin (x| N (>> 1 N))) )
|
||||
|
||||
(de grayDecode (G)
|
||||
(bin
|
||||
(pack
|
||||
(let X 0
|
||||
(mapcar
|
||||
'((C) (setq X (x| X (format C))))
|
||||
(chop G) ) ) ) ) )
|
||||
4
Task/Gray-code/PicoLisp/gray-code-2.l
Normal file
4
Task/Gray-code/PicoLisp/gray-code-2.l
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
(prinl " Binary Gray Decoded")
|
||||
(for I (range 0 31)
|
||||
(let G (grayEncode I)
|
||||
(tab (4 9 9 9) I (bin I) G (grayDecode G)) ) )
|
||||
18
Task/Gray-code/PowerBASIC/gray-code.basic
Normal file
18
Task/Gray-code/PowerBASIC/gray-code.basic
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
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
|
||||
10
Task/Gray-code/Prolog/gray-code-1.pro
Normal file
10
Task/Gray-code/Prolog/gray-code-1.pro
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
to_gray(N, G) :-
|
||||
N0 is N >> 1,
|
||||
G is N xor N0.
|
||||
|
||||
from_gray(G, N) :-
|
||||
( G > 0
|
||||
-> S is G >> 1,
|
||||
from_gray(S, N0),
|
||||
N is G xor N0
|
||||
; N is G ).
|
||||
31
Task/Gray-code/Prolog/gray-code-2.pro
Normal file
31
Task/Gray-code/Prolog/gray-code-2.pro
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
:- use_module(library(apply)).
|
||||
|
||||
to_gray(N, G) :-
|
||||
N0 is N >> 1,
|
||||
G is N xor N0.
|
||||
|
||||
from_gray(G, N) :-
|
||||
( G > 0
|
||||
-> S is G >> 1,
|
||||
from_gray(S, N0),
|
||||
N is G xor N0
|
||||
; N is G ).
|
||||
|
||||
make_num(In, Out) :-
|
||||
atom_to_term(In, Out, _),
|
||||
integer(Out).
|
||||
|
||||
write_record(Number, Gray, Decoded) :-
|
||||
format('~w~10|~2r~10+~2r~10+~2r~10+~w~n',
|
||||
[Number, Number, Gray, Decoded, Decoded]).
|
||||
|
||||
go :-
|
||||
setof(N, between(0, 31, N), Numbers),
|
||||
maplist(to_gray, Numbers, Grays),
|
||||
maplist(from_gray, Grays, Decodeds),
|
||||
format('~w~10|~w~10+~w~10+~w~10+~w~n',
|
||||
['Number', 'Binary', 'Gray', 'Decoded', 'Number']),
|
||||
format('~w~10|~w~10+~w~10+~w~10+~w~n',
|
||||
['------', '------', '----', '-------', '------']),
|
||||
maplist(write_record, Numbers, Grays, Decodeds).
|
||||
go :- halt(1).
|
||||
31
Task/Gray-code/PureBasic/gray-code.basic
Normal file
31
Task/Gray-code/PureBasic/gray-code.basic
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
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
|
||||
17
Task/Gray-code/Python/gray-code-1.py
Normal file
17
Task/Gray-code/Python/gray-code-1.py
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
def gray_encode(n):
|
||||
return n ^ n >> 1
|
||||
|
||||
def gray_decode(n):
|
||||
m = n >> 1
|
||||
while m:
|
||||
n ^= m
|
||||
m >>= 1
|
||||
return n
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("DEC, BIN => GRAY => DEC")
|
||||
for i in range(32):
|
||||
gray = gray_encode(i)
|
||||
dec = gray_decode(gray)
|
||||
print(f" {i:>2d}, {i:>05b} => {gray:>05b} => {dec:>2d}")
|
||||
17
Task/Gray-code/Python/gray-code-2.py
Normal file
17
Task/Gray-code/Python/gray-code-2.py
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
>>> def int2bin(n):
|
||||
'From positive integer to list of binary bits, msb at index 0'
|
||||
if n:
|
||||
bits = []
|
||||
while n:
|
||||
n,remainder = divmod(n, 2)
|
||||
bits.insert(0, remainder)
|
||||
return bits
|
||||
else: return [0]
|
||||
|
||||
|
||||
>>> def bin2int(bits):
|
||||
'From binary bits, msb at index 0 to integer'
|
||||
i = 0
|
||||
for bit in bits:
|
||||
i = i * 2 + bit
|
||||
return i
|
||||
7
Task/Gray-code/Python/gray-code-3.py
Normal file
7
Task/Gray-code/Python/gray-code-3.py
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
>>> def bin2gray(bits):
|
||||
return bits[:1] + [i ^ ishift for i, ishift in zip(bits[:-1], bits[1:])]
|
||||
|
||||
>>> def gray2bin(bits):
|
||||
b = [bits[0]]
|
||||
for nextb in bits[1:]: b.append(b[-1] ^ nextb)
|
||||
return b
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue