# Verilog 有符号数与无符号数运算

1. 无符号数运算，左值位宽不够，发生截断的现象
reg      [3:0]     a = 4'b1111;//15
reg      [3:0]     b = 4'b0010;//2
wire     [3:0]     c;
wire     [3:0]     show_c;
//17 10001
assign c = a + b;//1
assign show_c = a + b;//1


2. 两个无符号数运算，赋值给一个有符号的数。可以看出，右侧先按照无符号数进行运算，取得的运算结果按照左侧的符号进行数据显示。

reg               [3:0]     a = 15;//4'b1111
reg               [3:0]     b = 2;//4'b0010
reg  signed       [3:0]     c;
reg  signed       [4:0]     d;
reg  signed       [4:0]     e;

initial begin

c = a + b;
d = a + b;
e = b - a;
//17 10001
$display("c = %d",c); //1 0001$display("d = %d",d);     //-15  10001
$display("e = %d",e); //-13 10011 end  3. 两个无符号数运算，无符号数赋负值（补码）。按照该补码对应的正值进行处理。结果同上。 reg [3:0] a = -1;//4'b1111 15 reg [3:0] b = 2 ;//4'b0010 wire signed [3:0] c; wire signed [3:0] show_c; wire signed [4:0] d; wire signed [4:0] show_d; //17 10001 assign c = a + b;//0001 assign show_c = a + b;//1 assign d = a + b;//10001 assign show_d = a + b; //-15 signed  4. 有符号数和无符号数运算，赋值给有符号数。补码进行运算，如果左值位宽不够，进行截位，取得的结果为：3（4’b0011）。位宽足够，取得结果为-13（10011）。 reg signed [4:0] a = -15;//5'b10001 reg [3:0] b = 2;//4'b0010 wire signed [3:0] c; wire signed [3:0] show_c; wire signed [4:0] d; wire signed [4:0] show_d; assign c = a + b;//0011 assign show_c = a + b;//3 assign d = a + b;//10011 assign show_d = a + b; //-13  5. 有符号数和无符号数的比较 一个无符号数和一个有符号数比较，都视为无符号数，按照各自补码的大小进行比较； reg [3:0] a = 15;//4'b1111 reg [3:0] b = 14;//4'b1110 reg signed [3:0] c =-1 ;//4'b1111 reg signed [4:0] d =-2; //5'b11110 initial begin if(a <= c) begin$display("a <= c");//成立
end
if(b <= c) begin
$display("b <= c");//成立 end if(c > d) begin$display("c > d");//成立
end
end


6. 两个无符号数已经进行移位。数据先按照左值进行截断，然后再进行移位。算数右移时，不管左值是否有符号，都按照无符号数进行补零操作。

reg               [3:0]     a = 15;//4'b1111
reg               [3:0]     b = 4;//4'b0100
reg               [3:0]     c ;
reg  signed       [3:0]     d ;
reg  signed       [4:0]     e ;
reg  signed       [4:0]     f;

initial begin

c = ( a + b ) >> 1;
d = ( a + b ) >> 1;
e = ( a + b ) >> 1;
f = ( a + b ) >>> 1;

$display("c = %d",c);//1 0001$display("d = %d",d);//1 0001
$display("e = %d",e);//9 1001$display("f = %d",f);//9 1001


7.有符号数进行移位。只有参与运算的两个数都是有符号数，才按照有符号数进行算数右移，补最高位。不然，就补0.

reg  signed       [3:0]     a = -7;//4'b1001
reg               [3:0]     b = 4;//4'b0100
reg  signed       [3:0]     c = 4;//4'b0100
reg  signed       [3:0]     d ;
reg  signed       [3:0]     e ;
reg  signed       [3:0]     f;

initial begin

d = ( a + b ) >> 1;//a + b =-3 1101
e = ( a + b ) >>> 1;
f = ( a + c ) >>> 1;

$display("d = %d",d);//6 0110$display("e = %d",e);//6 0110
\$display("f = %d",f);//-2 1110


04-16 9206

02-01 1046

03-13 1万+

08-02 6840

04-04 829

02-22 7702

03-13 4102

03-07 4095

05-31 197

#### verilog有符号数使用方法简介

©️2020 CSDN 皮肤主题: 游动-白 设计师: 上身试试

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。