实现有符号补码数据比较
首先比较两个数据最高位(符号位),最高位一致情况下比较后四位。如果后四位谁大,则该数据大
module max_op(
input clk,rst_n,
input [4:0] a,
input [4:0] b,
output reg [4:0] out
);
reg cmd_flag;
always @(posedge clk or negedge rst_n)begin //确定输入的数据最高位是否一致
if(!rst_n)
cmd_flag <= 0;
else begin
if(a[4] != b[4]) //最高位不一致情况下判断谁为整数谁大
cmd_flag <= 1;
else
cmd_flag <= 0; //最高位一致情况下判断除去符号为剩余位,剩余位大的该数大
end
end
always@(posedge clk or negedge rst_n) begin
if(!rst_n)
out <= 5'b0;
else begin
if(cmd_flag)begin
if(a[4] == 0)
out <= a;
else
out <= b;
end
else begin
if(a[3:0] > b[3:0])
out <= a;
else
out <= b;
end
end
end
endmodule
测试代码
module tb_max_op;
// Inputs
reg clk;
reg rst_n;
reg [4:0] a1;
reg [4:0] b1;
// Outputs
wire [4:0] out;
// Instantiate the Unit Under Test (UUT)
max_op uut (
.clk(clk),
.rst_n(rst_n),
.a(a1),
.b(b1),
.out(out)
);
always #10 clk = ~clk;
initial begin
clk = 0;
rst_n = 0;
a1 = 0;
b1 = 0;
#100 rst_n = 1;
#200 a1 = 5'b11000;
b1 = 5'b11001;
#200 a1 = 5'b11001;
b1 = 5'b01000;
#200 a1 = 5'b01010;
b1 = 5'b00111;
end
endmodule