问题
I'm trying to solve some exercises, I have to shift a 8-bit vector named A into 2A (A+A).
my soluction for this is: (A(7) and '1') & A(6 downto 0) & '0';
after this I made a two's complement of A in this way:
entity complementare is
port(a: in std_logic_vector(7 downto 0);
b: out std_logic_vector(7 downto 0));
end complementare;
architecture C of complementare is
signal mask, temp: std_logic_vector(7 downto 0);
component ripplecarry8bit is
port(a,b: std_logic_vector(7 downto 0);
cin: in std_logic;
cout: out std_logic;
s: out std_logic_vector(7 downto 0));
end component;
begin
mask<="11111111";
temp<=a nand mask;
rc: ripplecarry8bit port map(temp, "00000001", '0', cout, b);
end C;
--if you need I post ripplecarry code but consider it as a generic adder
To get -2A (-A-A)
I was thinking to do this:
signal compA: std_logic_vector(7 downto 0);
compA: complementar port map(A, compA);
--shifting
(compA(7) and '1') & compA(6 downto 0) & '0'; -- -A
Now, my main doubt is about -A
, after using complementar and after getting compA, I have to extend 8-bit vector into 9-bit vector (cause my output has to be 9-bit vector), I was thinking to do this but I have doubts:
'1' & compA; --or should I just append compA to a '0' value?
回答1:
Simple signed arithmetics solutions for your problem :
For a signal A
which is an std_logic_vector
of a size C_SIZEOF_A
signal A : std_logic_vector(C_SIZEOF_A-1 downto 0);
To get a signal equal to -A (same size):
Complement the signal value and add one to this result:
signal minus_A : std_logic_vector(C_SIZEOF_A-1 downto 0);
minus_A <= (not A) + 1; -- Warning here !!!
Warning: The '+' operator is not defined for std_logic_vector. You do the addition with the solution you prefer. I intentionaly don't want to give a solution here because the simplest one is to use signed
signals but you said you can't.
To multiply a signal by 2 (signed or unsigned)
Add a null bit as LSB:
signal 2A : std_logic_vector(C_SIZEOF_A downto 0);
2A <= A & '0';
To extend a signal for 1 bit (signed) :
The MSB is the sign bit. Extend only this bit:
signal A_extended : std_logic_vector(C_SIZEOF_A downto 0);
A_extended <= A(C_SIZEOF_A-1) & A;
To extend a signal for 1 bit (unsigned) :
No sign bit here, simply add a '0':
signal A_extended : std_logic_vector(C_SIZEOF_A downto 0);
A_extended <= '0' & A;
来源:https://stackoverflow.com/questions/50580896/left-shifting-of-a-twos-complement-vector-vhdl