Binary to Gray Code Conversion in VHDL

This article presents VHDL source code for converting binary numbers to Gray code.

VHDL Code

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity BinarytoGray is
    port(
        b: in  std_logic_vector(3 downto 0);  -- binary input
        g: out std_logic_vector(3 downto 0)   -- gray code output
    );
end BinarytoGray;

architecture behavioral of BinarytoGray is
begin
    g(3) <= b(3);
    g(2) <= b(3) xor b(2);
    g(1) <= b(2) xor b(1);
    g(0) <= b(1) xor b(0);
end behavioral;

Explanation

The VHDL code defines an entity called BinarytoGray with a 4-bit binary input b and a 4-bit Gray code output g. The architecture behavioral implements the conversion logic.

The core of the conversion relies on the following relationship:

  • The most significant bit (MSB) of the Gray code is the same as the MSB of the binary number.
  • For the remaining bits, each Gray code bit is the exclusive OR (XOR) of the corresponding binary bit and the binary bit to its left.

This is reflected in the following assignments:

  • g(3) <= b(3); (MSB remains the same)
  • g(2) <= b(3) xor b(2);
  • g(1) <= b(2) xor b(1);
  • g(0) <= b(1) xor b(0);

This code snippet provides a simple and efficient implementation of binary to Gray code conversion in VHDL.