Verilog 如何处理负数? [英] How does Verilog behave with negative numbers?
问题描述
例如,假设我有一个 reg [7:0] myReg
我给它赋值 -8'D69
For instance, say I have a reg [7:0] myReg
I assign it the value -8'D69
我知道 Verilog 将它存储为 2 的补码,所以它应该存储为
I know Verilog stores it as 2's complement so it should be stored as
10111011
我现在的问题是是否要对其执行操作,例如 myReg/2
The question I have now is if I were to perform an operation on it, say myReg/2
它会评估为 -34 吗?还是需要将 10111011 变成 187 然后进行除法,返回 93?
Would it evaluate to -34? Or would it take 10111011 and turn it into 187 then perform the division, returning 93?
推荐答案
你需要记住 -8d69
只是一个位模式.reg 是一种保存位模式的类型.它是指示 /
执行有符号或无符号算术运算的变量类型.
You need to remember that -8d69
is just a bit pattern. reg is a type which holds bit patterns. It is the type of variable that instructs /
to perform signed or unsigned arithmetic.
如果这是为了综合考虑您想尝试避免使用分隔符,那么您真的想尝试避免使用带符号的分隔符.它可能会用 >>>> 合成更小.1
If this is for synthesis bare in mind that you want to try and avoid dividers, you really want to try and avoid signed dividers. It will likely synthesis smaller with >>> 1
reg [7:0] a;
reg signed [7:0] b;
reg [7:0] c;
reg signed [7:0] d;
initial begin
a = -8'd69 ;
b = -8'd69 ;
c = -8'd69 ;
d = -8'd69 ;
#10ns;
a = a/2 ;
b = b/2 ;
#10ns;
$display("a : %8b, %d", a, a);
$display("b : %8b, %d", b, b);
$display("c >>>1 : %8b, %d", c>>>1, c>>>1);
$display("d >>>1 : %8b, %d", d>>>1, d>>>1);
end
给出:
a : 01011101, 93
b : 11011110, -34
c >>>1 : 01011101, 93
d >>>1 : 11011101, -35
<代码>>>x 右移 x 位,>>>>x
右移 x 位,但符号扩展为有符号类型.
>> x
Shifts right by x places, >>> x
Shifts right x places but sign extends for signed types.
注意:/2
在我的示例中也会四舍五入,>>>
将向下舍入/截断.
NB: the /2
is also rounding up in my examples, >>>
will round down/truncate.
这篇关于Verilog 如何处理负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!