Skip to content

Instantly share code, notes, and snippets.

@GaryLee
Last active January 18, 2026 08:46
Show Gist options
  • Select an option

  • Save GaryLee/984336b20057d6c837b776add6f9233b to your computer and use it in GitHub Desktop.

Select an option

Save GaryLee/984336b20057d6c837b776add6f9233b to your computer and use it in GitHub Desktop.
Add a unsigned and signed value. Check if the result if overflow or underflow.
/// Signed extension macro. The add_width must be larger than 1.
`define SIGNEXT(signal, from_width, add_width) {{(add_width){signal[(from_width)-1]}}, signal}
/// Unsigned extension macro. The add_width must be larger than 1.
`define ZEROEXT(signal, from_width, add_width) {{(add_width){1'b0}}, signal}
module value_adder #(BITS=16) (
input logic [BITS-1:0] a, // Unsigned.
input logic [BITS-1:0] b, // Signed.
output logic [BITS-1:0] c,
output logic overflow,
output logic underflow
);
logic [BITS+1:0] sum;
sum = `ZEROEXT(a, BITS, 1) + `SIGNEXT(b, BITS, 1);
c[BITS-1:0] = sum[BITS-1:0];
underflow = b[BITS-1] & sum[BITS];
overflow = ~b[BITS-1] & sum[BITS];
endmodule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment