如何在VHDL中将字符串转换为整数?

6

我正在将文本数据加载到VHDL测试台中,我想将输入字符串转换为整数值。

例如:"123" => 123

有人能推荐一种在VHDL中将字符串转换为整数的“最佳”方法吗?

2个回答

6

为了参考。也可以使用'value属性将字符串转换为整数:

variable str : string := "1234";
variable int : integer;
...

int := integer'value(str);

根据需求,这可能比read()过程更可取,因为它不会破坏源字符串。然而,它只能在字符串是一个有效的整数文字,且没有空格之外的周围字符时工作。

variable ln  : line;
variable int : integer;
...

ln := new string'("  456   ");  -- Whitespace will be ignored
int := integer'value(ln.all); -- Doesn't consume contents of ln

ln := new string'("789_000 more text");
int := integer'value(ln.all); -- This will fail unlike read()

+1,但值得注意的是,这两个选项都不受综合工具的良好支持。Vivado 2020.1无法综合任何一个选项。对于可综合代码,我只编写了一个小解析器,使用character'pos(x(i)) - character'pos('0')将每个数字转换。别忘了减号。 - Harry

5

readlineread函数应该可以实现您正在寻找的功能。

基本上:

  1. 打开文件
  2. 使用readline从文件中获取下一行到行缓冲区
  3. 使用read解析行缓冲区以获取有用数据
  4. (可选)根据需要转换已解析的值

代码片段:

library STD;
use std.textio.all;
...
variable File_Name         : string;
file my_file               : text; 
variable lineptr           : line;
variable temp              : integer;
...
file_open(my_file, File_Name, read_mode); -- open the file
readline(my_file, lineptr); -- put the next line of the file into a buffer
read(lineptr, temp); -- "parse" the line buffer to an integer
-- temp now contains the integer from the line in the file
...

那位先生给出了一个美味的答案。谢谢! - Tom Ravenscroft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接