Rebol3 Code Examplex


Gray code

A binary numbering scheme where consecutive values differ by only one bit.

Rebol [
    title: "Rosetta code: Gray code"
    file:  %Gray_code.r3
    url:   https://rosettacode.org/wiki/Gray_code
]

grey-encode: function [
    "Return the Grey code of n."
    n [integer!]
][
    n xor (n >> 1)  ;; XOR with right-shifted self
]

grey-decode: function [
    "Decode a Grey-coded integer back to binary."
    n [integer!]
][
    p: n
    n: n >> 1
    while [n != 0][
        p: p xor n
        n: n >>  1  ;; peel off one bit at a time
    ]
    p
]

for i 0 31 1 [
    g: grey-encode i
    b: grey-decode g
    print [
        pad i -2
        ":" enbase i 2 "⇾" enbase g 2 "⇾" enbase b 2 ":"
        pad b  2
    ]
]

Output:

 0 : 00000000 ⇾ 00000000 ⇾ 00000000 : 0 
 1 : 00000001 ⇾ 00000001 ⇾ 00000001 : 1 
 2 : 00000010 ⇾ 00000011 ⇾ 00000010 : 2 
 3 : 00000011 ⇾ 00000010 ⇾ 00000011 : 3 
 4 : 00000100 ⇾ 00000110 ⇾ 00000100 : 4 
 5 : 00000101 ⇾ 00000111 ⇾ 00000101 : 5 
 6 : 00000110 ⇾ 00000101 ⇾ 00000110 : 6 
 7 : 00000111 ⇾ 00000100 ⇾ 00000111 : 7 
 8 : 00001000 ⇾ 00001100 ⇾ 00001000 : 8 
 9 : 00001001 ⇾ 00001101 ⇾ 00001001 : 9 
10 : 00001010 ⇾ 00001111 ⇾ 00001010 : 10
11 : 00001011 ⇾ 00001110 ⇾ 00001011 : 11
12 : 00001100 ⇾ 00001010 ⇾ 00001100 : 12
13 : 00001101 ⇾ 00001011 ⇾ 00001101 : 13
14 : 00001110 ⇾ 00001001 ⇾ 00001110 : 14
15 : 00001111 ⇾ 00001000 ⇾ 00001111 : 15
16 : 00010000 ⇾ 00011000 ⇾ 00010000 : 16
17 : 00010001 ⇾ 00011001 ⇾ 00010001 : 17
18 : 00010010 ⇾ 00011011 ⇾ 00010010 : 18
19 : 00010011 ⇾ 00011010 ⇾ 00010011 : 19
20 : 00010100 ⇾ 00011110 ⇾ 00010100 : 20
21 : 00010101 ⇾ 00011111 ⇾ 00010101 : 21
22 : 00010110 ⇾ 00011101 ⇾ 00010110 : 22
23 : 00010111 ⇾ 00011100 ⇾ 00010111 : 23
24 : 00011000 ⇾ 00010100 ⇾ 00011000 : 24
25 : 00011001 ⇾ 00010101 ⇾ 00011001 : 25
26 : 00011010 ⇾ 00010111 ⇾ 00011010 : 26
27 : 00011011 ⇾ 00010110 ⇾ 00011011 : 27
28 : 00011100 ⇾ 00010010 ⇾ 00011100 : 28
29 : 00011101 ⇾ 00010011 ⇾ 00011101 : 29
30 : 00011110 ⇾ 00010001 ⇾ 00011110 : 30
31 : 00011111 ⇾ 00010000 ⇾ 00011111 : 31