Verilog:如何取绝对值 [英] Verilog: how to take the absolute value

查看:114
本文介绍了Verilog:如何取绝对值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 verilog 中,我有一个二进制值数组.如何取减去值的绝对值?

Verilog 代码:

module aaa(clk);输入时钟;reg [7:0] a [1:9];reg [7:0] s [1:9];总是@(posedge clk)开始s[1] = a[1] - a[2];s[2] = a[2] - a[3];s[3] = a[1] + a[3];结尾结束模块

我希望我的 s[1]s[2] 值总是.我怎样才能在可综合的 verilog 中做到这一点?

我尝试使用 signed reg,但显示错误.

解决方案

无论数字是否signed,仍然使用二进制补码,在位级别正确执行加减法.

如果要将数字解释为有符号数,则可以使用 MSB 来判断它是正数 (0) 还是负数 (1)

绝对数字只是根据 MSB 反转:

reg [31:0] ans ;//其他东西驱动这个值reg [31:0] abs_ans;//绝对版本的ans//反转(绝对值)总是@* 开始如果 (ans[31] == 1'b1) 开始abs_ans = -ans;结尾否则开始abs_ans = ans;结尾结尾

注意:使用 = 因为它是一个组合块,如果使用触发器(边沿触发器),请使用 <= 正如@TzachiNoy 所提到的.>

In verilog I have an array of binary values. How do I take the absolute value of the subtracted values ?

Verilog code:

module aaa(clk);
  input clk;

  reg [7:0] a [1:9];  
  reg [7:0] s [1:9];

  always@(posedge clk)  
  begin
    s[1] = a[1] - a[2];
    s[2] = a[2] - a[3];
    s[3] = a[1] + a[3];
  end
endmodule

I want my s[1] and s[2] values to be always positive. How can I do it in synthesisable verilog?

I have tried using signed reg, but it shows an error.

解决方案

Regardless of whether the number is signed or not twos complement is still used which correctly performs addition and subtraction at the bit level.

If a number is to be interpreted as signed the MSB can be used to tell if it is positive (0) or negative (1)

To absolute the number just invert based on the MSB:

reg [31:0] ans    ; // Something else drives this value
reg [31:0] abs_ans; // Absolute version of ans
// invert (absolute value)
always @* begin
  if (ans[31] == 1'b1) begin
    abs_ans = -ans;
  end
  else begin
    abs_ans = ans;
  end
end

NB: using = because it is a combinatorial block, if using a flip-flop (edge trigger) use <= as @TzachiNoy has mentioned.

这篇关于Verilog:如何取绝对值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆