为什么逻辑右移在这段代码中表现得像算术右移?
Why is logic right shift behaving like arithmetic right shift in this code?
我正在构建一个浮点加法器模块,其中一部分需要 2s 补码和移位值。主要模块代码为
module backup (x, y, z, clk);
input [7:0] x,y;
output reg [7:0] z;
input clk;
integer i;
reg [1:0] a;
reg unsigned [7:0] temp;
reg unsigned [8:0] temp2;
always @ (posedge clk) begin
a = 2'b00;
temp = 8'b00111100;
temp = ((~temp)+1) >> 2;
$display("temp = %b", temp);
end
endmodule
module backup_tb();
reg [7:0] x,y;
wire [7:0] z;
reg clk;
backup m1 (.x(x),.y(y),.z(z),.clk(clk));
always #10 clk = ~clk;
initial begin
clk = 0;
#50
$finish;
end
endmodule
此代码的输出是 temp = 11110001
,而预期输出是 temp = 00110001
。请解释我在这里遗漏了什么,或者我该如何解决?
问题不在于右移;它带有表达式 ((~temp)+1)
。您正在将 8 位操作数添加到 32 位操作数,并且操作数在执行任何操作之前 得到扩展。数字文字隐式为 32 位。所以按位 ~
操作反转 32'b00000000_00000000_00000000_00111100
然后右移。要修复它,你可以写:
temp = ((~temp)+1'b1) >> 2;
我正在构建一个浮点加法器模块,其中一部分需要 2s 补码和移位值。主要模块代码为
module backup (x, y, z, clk);
input [7:0] x,y;
output reg [7:0] z;
input clk;
integer i;
reg [1:0] a;
reg unsigned [7:0] temp;
reg unsigned [8:0] temp2;
always @ (posedge clk) begin
a = 2'b00;
temp = 8'b00111100;
temp = ((~temp)+1) >> 2;
$display("temp = %b", temp);
end
endmodule
module backup_tb();
reg [7:0] x,y;
wire [7:0] z;
reg clk;
backup m1 (.x(x),.y(y),.z(z),.clk(clk));
always #10 clk = ~clk;
initial begin
clk = 0;
#50
$finish;
end
endmodule
此代码的输出是 temp = 11110001
,而预期输出是 temp = 00110001
。请解释我在这里遗漏了什么,或者我该如何解决?
问题不在于右移;它带有表达式 ((~temp)+1)
。您正在将 8 位操作数添加到 32 位操作数,并且操作数在执行任何操作之前 得到扩展。数字文字隐式为 32 位。所以按位 ~
操作反转 32'b00000000_00000000_00000000_00111100
然后右移。要修复它,你可以写:
temp = ((~temp)+1'b1) >> 2;