VHDL测试台32位无符号整数字符串转换报错如何解决
问题根源
VHDL 预定义的integer类型为32位有符号数,标准规定取值范围为 -2147483648 到 2147483647。你需要解析的3413424693已经超出了这个上限,因此integer'value()方法无法完成字符串转换,直接触发报错。
解决步骤
- 替换类型:弃用
integer存储/转换数值,改用和模块输出匹配的32位无符号类型unsigned处理预期值。 - 新增转换逻辑:由于旧版VHDL没有内置的十进制字符串转
unsigned的方法,需要手动实现转换函数。 - 调整比对逻辑:直接比对
unsigned类型的实际输出和转换后的预期值。
具体修改代码
首先确保测试台开头已导入所需库:
use ieee.std_logic_1164.all; use ieee.numeric_std.all;
在架构体内(process外部)新增字符串转无符号数的辅助函数:
-- 十进制数字字符串转指定位宽的unsigned function str_to_unsigned(str : string; width : natural) return unsigned is variable res : unsigned(width-1 downto 0) := (others => '0'); variable digit : integer range 0 to 9; begin for idx in str'range loop -- 跳过空格等非数字字符 if str(idx) >= '0' and str(idx) <= '9' then digit := character'pos(str(idx)) - character'pos('0'); res := res * 10 + to_unsigned(digit, width); end if; end loop; return res; end function;
接着修改原有process代码:
process variable line_v : line; file read_file : text; variable read_string: string(1 to 10); -- 32位无符号最大值4294967295刚好10位 begin file_open(read_file, "mat2.mem", read_mode); for i in 0 to 31 loop for j in 0 to 31 loop readline(read_file, line_v); read(line_v, read_string); row <= std_logic_vector(TO_UNSIGNED(i, row'length)); col <= std_logic_vector(TO_UNSIGNED(j, col'length)); wait for 2 ns; -- 等待模块输出data有效 -- 替换原有的integer转换逻辑,直接比对unsigned类型 assert unsigned(data) = str_to_unsigned(read_string, 32) report "ERROR! Result not equal to expected one!" severity error; end loop; end loop; file_close(read_file); end process;
额外说明
- 如果你的仿真器支持VHDL-2008标准,可以直接用内置的
unsigned'value()方法替换自定义函数,代码更简洁:assert unsigned(data) = unsigned'value(read_string) report "ERROR! Result not equal to expected one!" severity error; - 注意不要用
natural类型替代,natural是integer的子类型,上限同样是2147483647,依然无法处理超过该值的无符号数。
内容的提问来源于stack exchange,提问作者Salvatore Gabriele La Greca
相关产品推荐
相关产品推荐

