How do I determine the number of address bits needed to address a memory


#1

Say I have a memory that is 10K deep. In SystemVerilog, is there an easy way to determine the width of the address bus needed to access this memory?


#2

The system function $clog2 helps you figure out the number of bits necessary to address a memory of a given size.

So you could code your RTL design like this:

module memory #(parameter MEM_SIZE=10000, MEM_WD=32)
(
    input  logic clk,
    input  logic rst,
    input  logic [$clog2(MEM_SIZE)-1:0] addr,
    input  logic [MEM_WD-1:0] data_in,
    input  logic wr,
    output logic [MEM_WD-1:0] data_out
);

logic [MEM_WD-1:0] mem[MEM_SIZE];

always_ff @(posedge clk) begin
    if (rst) begin
        data_out <= 'd0;
    end
    else begin
        if (wr) begin
            mem[addr] <= data_in;
        end
        else begin
            data_out <= mem[addr];
        end
    end
end
endmodule

Another Example:

$display("%m, @%0t: Bits are necessary to address a 100 deep memory: %0d", $time, $clog2(100));
#2ns;
$display("%m, @%0t: Bits are necessary to address a 10000 deep memory: %0d", $time, $clog2(10000));

Output:

utils, @0: Bits are necessary to address a 100 deep memory: 7
utils, @2: Bits are necessary to address a 10000 deep memory: 14