peaceman
peaceman

Reputation: 1721

Converting 8-bit two complement signed number to decimal

The task is larger but I'm stuck at converting from signed 8 bit two complement number to decimal. Here is some code:

entity example is
    Port ( switches : in STD_LOGIC_VECTOR (7 downto 0) );
end example;
signal integer_value : integer;

Logic I'm trying to use to convert this input to decimal is

integer_value <= to_integer(unsigned(switches));

integer_value ends up being either zero or minimum value for integer (-2147483648). Example input would be "01101111".

Upvotes: 0

Views: 873

Answers (1)

Morten Zilmer
Morten Zilmer

Reputation: 15924

Use signed, not unsigned, thus as:

integer_value <= to_integer(signed(switches));

Consider making a small test bench to experiment with the construction, so you isolate the problem, since it sounds like the issue is elsewhere in the design. Simple test bench may be like:

entity mdl_tb is
end entity;

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

architecture sim of mdl_tb is
  signal switches      : std_logic_vector(7 downto 0);
  signal integer_value : integer;
begin

  integer_value <= to_integer(signed(switches));

  process is
  begin
    switches <= "00000000"; wait for 10 ns; report integer'image(integer_value);
    switches <= "11111111"; wait for 10 ns; report integer'image(integer_value);
    switches <= "10000000"; wait for 10 ns; report integer'image(integer_value);
    switches <= "01101111"; wait for 10 ns; report integer'image(integer_value);
    wait;
  end process;

end architecture;

and this outputs:

# ** Note: 0
#    Time: 10 ns  Iteration: 0  Instance: /mdl_tb
# ** Note: -1
#    Time: 20 ns  Iteration: 0  Instance: /mdl_tb
# ** Note: -128
#    Time: 30 ns  Iteration: 0  Instance: /mdl_tb
# ** Note: 111
#    Time: 40 ns  Iteration: 0  Instance: /mdl_tb

Upvotes: 1

Related Questions