The GRAY code

published: 21 December 2024 / updated 21 December 2024

Lire cette page en français

 

article: 02 mai 2018 / mis à jour 29 aout 2019

Gray's code, also called gray code or binary code, is a type of coding binary allowing you to modify only one bit at a time when a number is increased by one unit. This property is important for many applications.

pIn normal binary:

0    000
1    001     change of one bit
2    010     change of two bits
3    011     change of one bit
4    100     change of three bits
5    101     change of one bit
6    110     change of two bits
7    111     change of one bit

In Gray code:

0    000
1    001
2    011
3    010
4    110
5    111
6    101
7    100

The transition between each sequence only changes one bit. We can even loop 7 with 0

: >gray ( n -- n' ) 
    dup 2/ xor ;    \ n' = n xor ( décalage logique vers la droite 1x )   
 
: gray> ( n -- n )
    0  1 31 lshift  ( -- g b mask )             
    begin
        >r          \ sauve mask sur pile retour
        2dup 2/ xor
        r@ and or                               
        r> 1 rshift
        dup 0=
    until
    drop nip ;      \ nettoie pile de données en laissant le résultat
 
: test
    2 base !        \ sélectionne base binaire
    32 0 do
        cr I  dup 5 .r ."  ==> "    \ affiche valeurs (binaire) 
        >gray dup 5 .r ."  ==> "    \ justifiés à droite sur 5 caractères
        gray>     5 .r
    loop
    decimal ;         \ remet en décimal
code GRAY dans une roue codeuse

Execution of test:

test
    0 ==>     0 ==>     0
    1 ==>     1 ==>     1
   10 ==>    11 ==>    10
   11 ==>    10 ==>    11
  100 ==>   110 ==>   100
  101 ==>   111 ==>   101
  110 ==>   101 ==>   110
  111 ==>   100 ==>   111
 1000 ==>  1100 ==>  1000
 1001 ==>  1101 ==>  1001
 1010 ==>  1111 ==>  1010
 1011 ==>  1110 ==>  1011
 1100 ==>  1010 ==>  1100
 1101 ==>  1011 ==>  1101
 1110 ==>  1001 ==>  1110
 1111 ==>  1000 ==>  1111
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 ok

Gray code applications

The Gray code is also used in Karnaugh tables used in the design of logic circuits: Karnaugh Table

The Gray code is also used for encoder wheels. Transitions are in GRAY code avoiding sequences random parasites: Encoded wheel