问题描述
我有一个负数(MSB=1).如何通过在 VHDL 中移位来将数字除以 2 .
I have a negative number(MSB=1). How can I divide the number by, say 2 , by shifting in VHDL.
例如.移动 -6 应该给我 2.
Eg. shifting -6 should give me 2.
我如何概括划分/移位例如:- -6 -> -36 -> 3
How can I generalize the division/shifteg:- -6 -> -3 6 -> 3
推荐答案
对于使用 ieee.numeric_std.signed
在二进制补码中除以 2 的数字(负数和正数)可以使用移动:
For division by 2 of numbers (both negative and positive) in two's complement using ieee.numeric_std.signed
it can be done using shift with:
res <= std_logic_vector(shift_right(signed(arg), 1));
带符号参数的 shift_right
将进行算术移位,因此对于除以 2 并移位一位非常有用.
The shift_right
with signed argument will do arithmetic shifting, thus useful for division by 2 with a single bit shifted.
正如 MatthiasB 在评论中指出的那样,也可以使用除法,其中:
As MatthiasB points out in the comment, then division can also be used, with:
res <= std_logic_vector(signed(arg) / 2);
操作上的区别是:
- Shift (
shift_right
):向下取整,因此 -7/2 = -4 - 除法 (
/
):向零舍入,因此 -7/2 = -3
- Shift (
shift_right
): Round down, thus -7 / 2 = -4 - Division (
/
): Rounds towards zero, thus -7 / 2 = -3
实现上的差异:
- Shift (
shift_right
):尺寸和速度为零,因为只需要布线 - 除法 (
/
):在大小和速度上有一些成本,因为四舍五入需要逻辑运算
- Shift (
shift_right
): Zero cost in size and speed, since done with wiring only - Division (
/
): Some cost in size and speed, since logic operations are required for rounding
这篇关于通过移位在 VHDL 中除负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!