说明
基于Verilog HDL实现4位二进制阶乘运算
功能
输入(n):4位二进制
输出(result):32位二进制
源代码
module fanctorial (
clk,
rst_n,
n,
result
);
parameter WIDTH_IN = 4;
parameter WIDTH_OUT = 32;
input clk, rst_n;
input [WIDTH_IN - 1:0] n;
output [WIDTH_OUT - 1:0] result;
reg [WIDTH_OUT - 1:0] result;
function [WIDTH_OUT - 1:0] fact;
input [WIDTH_IN - 1:0] op;
reg [WIDTH_IN - 1:0] ina;
begin
fact = op ? 1 : 0;
for(ina = 2; ina < op + 1; ina = ina + 1)
fact = ina * fact;
end
endfunction
always @(posedge clk or negedge rst_n) begin
if(~rst_n) begin
result <= 1'b0;
end else begin
result <= fact(n);
end
end
endmodule
源代码
testbench:
`timescale 1ns/1ns
module tb_fanctorial;
parameter WIDTH_IN = 4;
parameter WIDTH_OUT = 32;
reg clk, rst_n;
reg [WIDTH_IN - 1:0] n;
wire [WIDTH_OUT - 1:0] result;
fanctorial FANCTORAIL1(
.clk (clk),
.rst_n (rst_n),
.n (n),
.result (result)
);
parameter CYCLE = 10;
initial begin
clk = 0;
forever begin
#(CYCLE / 2)
clk = ~clk;
end
end
function [WIDTH_IN - 1:0] rands;
input [WIDTH_IN - 1:0] cyc;
begin
rands = {$random} % cyc;
end
endfunction
parameter DELAY = 100;
initial begin
rst_n = 0;
#DELAY
rst_n = 1;
end
initial begin
n = 0;
repeat(5) begin
#DELAY
n = rands(4'b1111);
end
#DELAY
$display("Function fanctorail simed over!");
$finish;
end
endmodule