0
\$\begingroup\$

I'm creating an ALU in Verilog, and I would like overflow to be dealt with by wrapping around to lower values.

For example:

0000_0001 + ffff_ffff == 0000_0001
0000_0011 + ffff_ffff == 0000_0011
0000_0012 + ffff_fffe == 0000_0011

Is it possible to achieve this in Verilog?

\$\endgroup\$
12
  • 3
    \$\begingroup\$ Are you sure you want 0000_0001 + ffff_ffff to be 0000_0001 and not 0000_0000 (which is what you'd get in typical integer arithmetic on a computer)? What result do you want for ffff_ffff + 0000_0000? \$\endgroup\$
    – The Photon
    Commented Sep 5, 2023 at 14:56
  • 3
    \$\begingroup\$ Wrap-around is typical, but it doesn't give the results you say you want. Your first example would result in 0, not 1, for example. This would be considered "wrap-around". (or to make it more coceptually simple, mod-256 arithmetic). \$\endgroup\$
    – The Photon
    Commented Sep 5, 2023 at 14:59
  • 1
    \$\begingroup\$ What @ThePhoton is talking about is that normally adding one to the highest unsigned integer yields the smallest unsigned integer, i.e. zero. Your question proposes a wrap-around to one, skipping the zero in between (thus actually incrementing by two). Normally, the result of wrap-around is the same as if you did the addition in a wider type and then just trimmed off the excess high-order bits again. \$\endgroup\$
    – TooTea
    Commented Sep 5, 2023 at 14:59
  • 1
    \$\begingroup\$ What you're asking for is what you'd get if you treat treat these values as signed integers with 1's-complement representation. (This is also a hint as to how to implement it in Verilog, but I don't know if you've shared enough to know that this solution will work for all the corner cases you need to have working) \$\endgroup\$
    – The Photon
    Commented Sep 5, 2023 at 15:03
  • 2
    \$\begingroup\$ It would help us to see the wording of the problem you actually need to solve. It's possible that they are, in a roundabout way, actually asking your to implement a 1's complement ALU. \$\endgroup\$
    – The Photon
    Commented Sep 5, 2023 at 15:05

1 Answer 1

1
\$\begingroup\$

Verilog arithmetic is defined for 2's complement numbers. If you want to perform 1's complement arithmetic, you need to convert the numbers first.

module top;
  
  function [31:0] comp  (reg [31:0] in);
    if (in[31]) 
      comp = -(~in);
    else
      comp = in;
  endfunction
  
  
  reg [31:0] A,B;
  initial begin
    A = 32'h0000_0012; B = 32'hffff_fffe;
    $displayh(comp(A) + comp(B));
  end
endmodule
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.