這個疑問困惑了我很久,直到我寫了加法器驗證了之後,才豁然開朗,原來自己在鑽牛角尖。怎麼講呢?既然結果也是有符號數,那麼它自然就代表乙個數的補碼。比如,我們需要用原碼表示乙個數-5,那麼可以表示為4'b1101;那麼補碼就會表示為4'b1011。換言之,如果結果是補碼形式4'b1011,verilog就已經把它看成-5了。不需要我們再人為轉換成原碼。
//--------------------------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 a = %b b = %d b = %b out = %d out = %b",a,a,b,b,out,out);
#1 a = -4'd2;
b = -4'd3;
$monitor("a = %d a = %b b = %d b = %b out = %d out = %b",a,a,b,b,out,out);
#1 a = 4'b1100;
b = 4'b1111;
$monitor("a = %d a = %b b = %d b = %b out = %d out = %b",a,a,b,b,out,out);
#1 a = 4'b1010;
b = 4'b1011;
$monitor("a = %d a = %b b = %d b = %b out = %d out = %b",a,a,b,b,out,out);
#1 a = 4'd2;
b = 4'd3;
$monitor("a = %d a = %b b = %d b = %b out = %d out = %b",a,a,b,b,out,out);
#1 a = 4'd4;
b = 4'd4;
$monitor("a = %d a = %b b = %d b = %b out = %d out = %b",a,a,b,b,out,out);
#1 a = 4'd6;
b = 4'd5;
#1 a = 4'd7;
$monitor("a = %d a = %b b = %d b = %b out = %d out = %b",a,a,b,b,out,out);
endadder u3 (.a(a),.b(b),.out(out));
endmodule
列印結果如下:
# a = -1 a = 1111 b = -7 b = 1001 out = -8 out = 111000
# a = -2 a = 1110 b = -3 b = 1101 out = -5 out = 111011
# a = -4 a = 1100 b = -1 b = 1111 out = -5 out = 111011
# a = -6 a = 1010 b = -5 b = 1011 out = -11 out = 110101
# a = 2 a = 0010 b = 3 b = 0011 out = 5 out = 000101
# a = 4 a = 0100 b = 4 b = 0100 out = 8 out = 001000
# a = 6 a = 0110 b = 5 b = 0101 out = 11 out = 001011
# a = 7 a = 0111 b = 5 b = 0101 out = 12 out = 001100
Verilog有符號數運算
在數位電路中,出於應用的需要,我們可以使用無符號數,即包括0及整數的集合 也可以使用有符號數,即包括0和正負數的集合。在更加複雜的系統中,也許這兩種型別的數,我們都會用到。有符號數通常以2的補碼形式來表示。圖1列出了4位二進位制表示法所對應正負數。進一步觀察,我們發現兩種型別數的加減法是一樣的,做加...
verilog有符號數的計算
看了許多關於有符號數計算的文章,這裡做一下總結。首先看看有符號數是如何儲存的,比如我們定義乙個位寬為8位的 a 10,通過 軟體可以看到它的表示為1111 0110,最高位是1代表有符號數,大小是它的反碼加1。接下來我們會分別做一下四個實驗 有符號數與無符號數的乘加計算和全是有符號數的乘加計算。1....
Verilog 有符號數與無符號數運算
無符號數運算,左值位寬不夠,發生截斷的現象 2.兩個無符號數運算,賦值給乙個有符號的數。可以看出,右側先按照無符號數進行運算,取得的運算結果按照左側的符號進行資料顯示。3.兩個無符號數運算,無符號數賦負值 補碼 按照該補碼對應的正值進行處理。結果同上。4.有符號數和無符號數運算,賦值給有符號數。補碼...