简单ALU
`timescale 1ns / 1ps
module ALU (
input [3:0] A,
input [3:0] B,
input [2:0] operation,
output reg [3:0] result,
output reg cout
);
always @(*) begin
cout = 0;
case (operation)
3'b000: begin
result <= A + B;
// 由于不能直接检测溢出,所以换一种方式检测
// 如果A + B > 1111 产生进位
if (A + B < A || A + B < B) cout = 1;
end
3'b001: begin
result <= A - B;
// 如果A - B < 0 产生借位
if (A < B) cout = 1;
end
3'b010: begin
result <= B + 1;
// 1111 + 1 产生进位
if (B == 4'b1111) cout = 1;
end
3'b011: begin
// 0 - 1 产生借位
result <= B - 1;
if (B == 4'b0000) cout = 1;
end
3'b100: begin
result <= ~A;
end
3'b101: begin
result <= A ^ B;
end
3'b110: begin
result <= A & B;
end
3'b111: begin
result <= A | B;
end
endcase
end
endmodule
testbench
`timescale 1ns / 1ps
module ALU_tb;
reg [3:0] A;
reg [3:0] B;
reg [2:0] operation;
wire [3:0] result;
wire cout;
ALU ALU (
A,
B,
operation,
result,
cout
);
initial begin
A <= 4'b0001;
B <= 4'b0010;
operation <= 000; // A + B 0011 没有进位
#10 A <= 4'b1100;
B <= 4'b1000;
operation <= 000; // A + B 0100 产生进位
#10 A <= 4'b0001;
B <= 4'b0001;
operation <= 001; // A - B 0000
#10 A <= 4'b0000;
B <= 4'b0001;
operation <= 001; // A - B < 0 1111 产生借位
#10 A <= 4'b0000;
B <= 4'b0001;
operation <= 010; // B + 1 0010
#10 A <= 4'b0000;
B <= 4'b1111;
operation <= 010; // B + 1 0000 产生进位
#10 A <= 4'b0000;
B <= 4'b0001;
operation <= 011; // B - 1 0000
#10 A <= 4'b0000;
B <= 4'b0000;
operation <= 011; // B - 1 1111 产生借位
#10 A <= 4'b1001;
B <= 4'b0001;
operation <= 100; //NOT A 0110
#10 A <= 4'b0001;
B <= 4'b0010;
operation <= 101; //A XOR B
#10 A <= 4'b0001;
B <= 4'b0001;
operation <= 110; //A AND B
#10 A <= 4'b0001;
B <= 4'b0000;
operation <= 110; //A AND B
#10 A <= 4'b0001;
B <= 4'b0000;
operation <= 111; //A OR B
#10 A <= 4'b0000;
B <= 4'b0000;
operation <= 111; //A OR B
#10 $stop;
end
endmodule
仿真图像
版权声明:本文为m0_46247741原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。