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

1.高位溢出赋给一个位宽不够的数

wire [3:0] a=4'b1111;//15
wire [3:0] b=4'b0010;//2
wire [3:0] c;

assign c = a + b;//17=10001

wire [3:0] a=4'b1111;
wire [3:0] b=4'b0010;
wire [2:0] c;

assign c = a + b;

2.高位溢出赋给一个位宽足够的数

wire [3:0] a=4'b1111;
wire [3:0] b=4'b0010;
wire [4:0] c;

assign c = a + b;

wire [3:0] a=4'b1111;
wire [3:0] b=4'b0010;
wire [5:0] c;

assign c = a + b; 

3.对中间结果移位

wire [3:0] a=4'b1111;
wire [3:0] b=4'b0010;
wire [3:0] c;

assign c =(( a + b) >> 1); //17=10001

wire [3:0] a=4'b1111;
wire [3:0] b=4'b0010;
wire [4:0] c;

assign c =(( a + b) >> 1); //17=10001

wire  [3:0] a=4'b1111;
wire  [3:0] b=4'b0010;
wire  [4:0] c;

assign c = ((a + b)>>>1) ; 

>>>算数右移，无符号数还是补0.

1.正常运算

wire signed [3:0] a=4'b1111;//-1
wire signed [3:0] b=4'b0010;//2
wire signed [3:0] c;

assign c =a + b;

wire signed [3:0] a=4'b1110;//-2
wire signed [3:0] b=4'b0001;//1
wire signed [3:0] c;

assign c =a + b;

2.赋给位宽不够的数

wire signed [3:0] a=4'b0111;//7
wire signed [3:0] b=4'b0010;//2
wire signed [3:0] c;

assign c =a + b; //9=1001

wire signed [3:0] a=4'b1001;//-7
wire signed [3:0] b=4'b1110;//-2
wire signed [3:0] c;

assign c =a + b;//-9=10111

3.赋给位宽足够的数

wire signed [3:0] a=4'b0111;
wire signed [3:0] b=4'b0010;
wire signed [4:0] c;

assign c =a + b;

wire signed [3:0] a=4'b1001;//-7
wire signed [3:0] b=4'b1110;//-2
wire signed [4:0] c;

assign c =a + b;//-9=10111

4.给中间结果移位

wire signed [3:0] a=4'b1001;//-7
wire signed [3:0] b=4'b1110;//-2
wire signed [3:0] c;

assign c =(( a + b ) >> 1); //-9=10111

wire signed [3:0] a=4'b1001;
wire signed [3:0] b=4'b1110;
wire signed [5:0] c;

assign c = ((a + b)>>1) ;

wire signed [3:0] a=4'b0111;//7
wire signed [3:0] b=4'b0010;//2
wire signed [3:0] c;

assign c =(( a + b ) >> 1);//9=01001

>>逻辑右移，高位都是都是补0。

wire signed [3:0] a=4'b1001;//-7
wire signed [3:0] b=4'b1110;//-2
wire signed [3:0] c;

assign c = ((a + b)>>>1) ; //-9=10111



>>>算数右移。截断赋值然后把最高位当符号位，补最高位。

wire signed [3:0] a=4'b1001;
wire signed [3:0] b=4'b1110;
wire signed [4:0] c;

assign c = ((a + b)>>>1) ; 

wire signed [3:0] a=4'b1001;
wire signed [3:0] b=4'b1110;
wire  [3:0] c,d;

assign c=a>>1;
assign d=a>>>1; 

>>逻辑右移，不管有符号还是无符号，都是补0。

>>>算术右移，补最高位。

1.只有两个操作数都是有符号数，才会把两个操作数都看作有符号数计算，否则无论是有符号数还是无符号数都会按照无符号数计算。

wire  [3:0] a=4'b1001;
wire signed [3:0] b=4'b1110;
wire signed [4:0] c;

assign c = ((a + b)>>>1);  //-9=10111

2.把a赋给b，若a是有符号数，则b高位用a的最高位填充，若a是无符号数，b的高位用0填充 。

wire  [3:0] a=4'b1001;
wire signed [3:0] b=4'b1001;
wire signed [4:0] c,d;

assign c=a;
assign d=b;