问题描述
我必须转换一个整数才能找到表示该整数需要多少位.假设整数值为 22.我知道表示这个整数需要 5 位.VHDL 中是否有任何属性可以执行此操作?重要提示:结果也应该是一个整数,代表位数.
I have to convert an integer to find how many bits are required to represent that integer.Let say, integer value is 22. I know 5 bits are required to represent this integer.Is there any attribute in VHDL to do this?Important: The result should also be an integer, which should represent number of bits.
推荐答案
没有 VHDL 属性或函数,但您可以创建一个函数,如:
There is no VHDL attribute or function, but you can create a function like:
-- Returns number of bits required to represent val in binary vector
function bits_req(val : natural) return natural is
variable res_v : natural; -- Result
variable remain_v : natural; -- Remainder used in iteration
begin
res_v := 0;
remain_v := val;
while remain_v > 0 loop -- Iteration for each bit required
res_v := res_v + 1;
remain_v := remain_v / 2;
end loop;
return res_v;
end function;
然而,有时 ceil_log2
函数也很有用,因为它根据内存映射中的条目给出所需的地址位数,并且 ceil_log2(val) = bits_req(val -1)
.
However, sometimes a ceil_log2
function is also useful, since that gives the number of required address bits based on entries in a memory map, and ceil_log2(val) = bits_req(val - 1)
.
这篇关于在 VHDL 中表示整数的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!