How to convert a string to integer in VHDL?
11,986
Solution 1
readline and read functions should achieve what you are looking for.
Basically:
- Open your file
- Use readline to get the next line from file into a line buffer
- Use read to parse the line buffer to useful data
- (Optional) convert the parsed value as necessary
Code Snippet:
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
...
Solution 2
For the sake of reference. It is also possible to convert a string to integer using the 'value
attribute:
variable str : string := "1234";
variable int : integer;
...
int := integer'value(str);
Depending on one's needs this may be more desirable than the read()
procedure because it does not destructively alter the source string. It does, however, only work if the string is a valid integer literal with no surrounding characters other than whitespace.
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()
Author by
Tom Ravenscroft
I'm an Engineering student at the University of Adelaide.
Updated on June 09, 2022Comments
-
Tom Ravenscroft almost 2 years
I am loading text data into a VHDL test bench and I want to convert input strings into integer values.
eg: "123" => 123
Can someone recommend a "best" way of converting strings to integers in VHDL?
-
Tom Ravenscroft over 12 yearsThat sir is a tasty answer. Thanks!
-
Harry over 2 years+1, but it is worth noting that neither option is well supported by synthesis tools. Vivado 2020.1 fails to synthesize either option. For synthesizable code, I just wrote a little parser that converts each digit using
character'pos(x(i)) - character'pos('0')
. And don't forget the minus sign.