Search code examples
vhdl

Russian peasant multiplication in VHDL always results in zero


I am implementing Russian peasant algorithm in VHDL. I have the following code.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity russian_peasant is
  port (
    multiplicand : in std_logic_vector(7 downto 0);
    multiplier : in std_logic_vector(7 downto 0);
    product : out std_logic_vector(15 downto 0)
  );
end entity;

architecture behavioral of russian_peasant is
begin
  process(multiplicand, multiplier)
    variable m : unsigned(7 downto 0) := unsigned(multiplicand);
    variable n : unsigned(7 downto 0) := unsigned(multiplier);
    variable p : unsigned(15 downto 0) := (others => '0');
  begin
    for i in 0 to 7 loop
      if m(i) = '1' then
        p := p + (n * 2**i);
      end if;
    end loop;
    product <= std_logic_vector(p);
  end process;
end architecture;

It compiles fine, but when I simulate it, why does it always yield zero as the result?

enter image description here


Solution

  • Your process has m, n and p variables that are initialized only in the process declarative part. These assignment are evaluated only once during elaboration (think at startup of simulation). They are not evaluated each time the process gets executed.

    You should probably rewrite the process with assignments as the first statements like:

      process(multiplicand, multiplier)
        variable m : unsigned(7 downto 0);
        variable n : unsigned(7 downto 0);
        variable p : unsigned(15 downto 0);
      begin
        m := unsigned(multiplicand);
        n := unsigned(multiplier);
        p := (others => '0');
        for i in 0 to 7 loop
          -- ...