Verilog: how to take the absolute value

Pravin shelton picture Pravin shelton · Oct 17, 2013 · Viewed 35.8k times · Source

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.

Answer

Morgan picture Morgan · Oct 22, 2013

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.