[Verilog] 最大値から必要な bit 幅を求める $clog2
システム関数 $clog2 が使えます。2 を底とする対数の天井関数の結果が得られます。
0〜N の値を表すのに必要な bit 幅は $clog2(N + 1) です。N 個の要素を指すインデックス(0〜N-1)なら $clog2(N) です。$clog2 は Verilog 2005(IEEE 1364-2005)で追加されました。
module m #(parameter max_count = 1023) (
input clk,
input rst_n,
input [$clog2(max_count + 1) - 1:0] in, // 0〜1023 → 10 bit
output [$clog2(max_count + 1) - 1:0] out
);
endmodule
See Also
- IEEE Std 1364™-2005: 17.11.1 Integer math functions
- IEEE Std 1800™-2012: 20.8.1 Integer math functions
