关于verilog中的有符号算数

  很多初学者总在纠结verilog的的有符号数代表的是原码还是补码。其实很简单,写个简单的半加器验证一一下就知道了。如半加器的源代码如下:

module Adder(
a,
b,
out);

input signed [3:0] a,b;
output  signed [5:0] out;

assign  out = a + b;

endmodule

测试平台如下:

//--------------------------Adder_tb.v-------------------------------
`timescale  1ns/1ns


module Adder_tb;
reg signed [3:0] a,b;
//reg   [3:0] b;
wire signed [5:0] out;

initial
begin
#1 a = -4'd1;
b = -4'd7;
$monitor("a = %d   b = %d  out = %d",a,b,out);  
#1 a = -4'd2;
b = -4'd3;
$monitor("a = %d   b = %d  out = %d",a,b,out);  
#1 a = 4'b1100;
b = 4'b1111;
$monitor("a = %d   b = %d  out = %d",a,b,out);  
#1 a = 4'b1010;
b = 4'b1011;
$monitor("a = %d   b = %d  out = %d",a,b,out);  
#1 a = 4'd2;
b = 4'd3;
$monitor("a = %d   b = %d  out = %d",a,b,out);  
#1 a = 4'd4;
b = 4'd4;
$monitor("a = %d   b = %d  out = %d",a,b,out);  
#1 a = 4'd6;
b = 4'd5;
#1 a = 4'd7;
$monitor("a = %d   b = %d  out = %d",a,b,out);
end

Adder  U3 (.a(a),.b(b),.out(out));

endmodule

仿真的结果如下:

# a =  -1   b =  -7  out =  -8
# a =  -2   b =  -3  out =  -5
# a =  -4   b =  -1  out =  -5
# a =  -6   b =  -5  out = -11
# a =   2   b =   3  out =   5
# a =   4   b =   4  out =   8
# a =   6   b =   5  out =  11
# a =   7   b =   5  out =  12

可以看到,-4以补码4'b1100表示出来;-1以补码4'b1111表示出来;-6以4'b1010表示;-5以4'b1011表示......并不是想象中的以符号位+绝对值得形式表示。




你可能感兴趣的:(关于verilog中的有符号算数)