有符号减法
有符号减法,从电路结构上讲,只要涉及到减法,理论上其得到的结果就是应该是一个有符号数,所以大家按照这个原则进行设计就行,如果需要对结果作转换,进行有符号到无符号转换即可,Verilog代码也推荐两种风格:
方式一:传统方式,手动扩位,实现左右位宽匹配,扩位为符号位,另外信号输入有符号数,一定要显示定义,Verilog默认不定义就是无符号类型
1 localparam A_WIDTH = 16;
2 localparam B_WIDTH = 8;
3 // Sumation result width should be 1 bit more than biggest widht of adder factor
4 localparam C_WIDTH = if (A_WIDTH > B_WIDTH) ? A_WIDTH + 1'b1 : B_WIDTH + 1'b1;
5
6 reg signed [A_WIDTH-1 : 0] a;
7 reg signed [B_WIDTH-1 : 0] b;
8
9 reg signed [C_WIDTH-1 : 0] c;
10 reg unsigned [C_WIDTH-1 : 0] c_unsigned;
11
12 always @(*) begin
13 c = {(C_WIDTH-A_WIDTH){a[A_WIDTH-1]}},a} -
{{C_WIDTH-B_WIDTH{b[B_WIDITH-1]}},b};
14 end
15
16 always @(*) begin
17 c_unsigned = {~c[C_WIDTH-1],c[C_WIDTH-2:0]};
18 end
方式二: Synopsys推荐,直接定义好符号类型,和的位宽按照运算法则定义好,实际+地方不作位宽匹配,工具自动识别
1 localparam A_WIDTH = 16;
2 localparam B_WIDTH = 8;
3 // Sumation result width should be 1 bit more than biggest widht of adder factor
4 localparam C_WIDTH = if (A_WIDTH > B_WIDTH) ? A_WIDTH + 1'b1 : B_WIDTH + 1'b1;
5
6 reg signed [A_WIDTH-1 : 0] a;
7 reg signed [B_WIDTH-1 : 0] b;
8
9 reg signed [C_WIDTH-1 : 0] c;
10 reg unsigned [C_WIDTH-1 : 0] c_unsigned;
11
12 always @(*) begin
13 c = $signed(a) - $signed(b);
14 end
16 always @(*) begin
17 c_unsigned = {~c[C_WIDTH-1],c[C_WIDTH-2:0]};
18 end
方式一:传统方式,手动扩位,实现左右位宽匹配,扩位为符号位,另外信号输入有符号数,一定要显示定义,Verilog默认不定义就是无符号类型
1 localparam A_WIDTH = 16;
2 localparam B_WIDTH = 8;
3 // Sumation result width should be 1 bit more than biggest widht of adder factor
4 localparam C_WIDTH = if (A_WIDTH > B_WIDTH) ? A_WIDTH + 1'b1 : B_WIDTH + 1'b1;
5
6 reg signed [A_WIDTH-1 : 0] a;
7 reg signed [B_WIDTH-1 : 0] b;
8
9 reg signed [C_WIDTH-1 : 0] c;
10 reg unsigned [C_WIDTH-1 : 0] c_unsigned;
11
12 always @(*) begin
13 c = {(C_WIDTH-A_WIDTH){a[A_WIDTH-1]}},a} -
{{C_WIDTH-B_WIDTH{b[B_WIDITH-1]}},b};
14 end
15
16 always @(*) begin
17 c_unsigned = {~c[C_WIDTH-1],c[C_WIDTH-2:0]};
18 end
方式二: Synopsys推荐,直接定义好符号类型,和的位宽按照运算法则定义好,实际+地方不作位宽匹配,工具自动识别
1 localparam A_WIDTH = 16;
2 localparam B_WIDTH = 8;
3 // Sumation result width should be 1 bit more than biggest widht of adder factor
4 localparam C_WIDTH = if (A_WIDTH > B_WIDTH) ? A_WIDTH + 1'b1 : B_WIDTH + 1'b1;
5
6 reg signed [A_WIDTH-1 : 0] a;
7 reg signed [B_WIDTH-1 : 0] b;
8
9 reg signed [C_WIDTH-1 : 0] c;
10 reg unsigned [C_WIDTH-1 : 0] c_unsigned;
11
12 always @(*) begin
13 c = $signed(a) - $signed(b);
14 end
16 always @(*) begin
17 c_unsigned = {~c[C_WIDTH-1],c[C_WIDTH-2:0]};
18 end