Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

$clog2: Memory Address Width

Verilog Math Functions

A parameterized memory whose address width comes from $clog2(DEPTH), with a small testbench

Open in IDE
design.v
module mem #(parameter DEPTH = 100, parameter WIDTH = 8)
  (input                      clk, we,
   input  [$clog2(DEPTH)-1:0] addr,
   input  [WIDTH-1:0]         wdata,
   output reg [WIDTH-1:0]     rdata);

  reg [WIDTH-1:0] ram [0:DEPTH-1];

  always @(posedge clk) begin
    if (we) ram[addr] <= wdata;
    rdata <= ram[addr];
  end
endmodule
testbench.v
module tb;
  reg        clk = 0;
  reg        we;
  reg  [6:0] addr;
  reg  [7:0] wdata;
  wire [7:0] rdata;

  mem #(.DEPTH(100), .WIDTH(8)) u0 (.clk(clk), .we(we), .addr(addr), .wdata(wdata), .rdata(rdata));

  always #5 clk = ~clk;

  initial begin
    $display("Address width for 100 entries = %0d", $clog2(100));
    we = 1; addr = 99; wdata = 8'hA5;
    @(posedge clk);
    #1 we = 0;
    @(posedge clk);
    #1 $display("ram[99] = 0x%0h", rdata);
    $finish;
  end
endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.