How to subtract two hexadecimal numbers in VHDL? - vhdl

I am reading two hex numbers from a text file and I want to be able to subtract the two numbers and place the result into another variable how would I go about doing this? Is it possible to make a function to do this that I can then place in a package file and reference so that my code is more readable and less cluttered?
many thanks,

For conversion of line to unsigned, VHDL-2008 provides a hread procedure in then numeric_bit package. A function that takes string and returns natural could look like:
library ieee;
use ieee.numeric_bit.all;
library std;
use std.textio.all;
...
function hex_to_nat(s : string) return natural is
variable line_v : line;
variable value_v : unsigned(4 * s'length - 1 downto 0); -- Bits to match value in hex
begin
line_v := new string'(s);
hread(line_v, value_v); -- Assertion in case of conversion error
deallocate(line_v); -- Avoid memory leak
return to_integer(value_v); -- Assertion in case of conversion error
end function;
If the text read from the file is already of line type, then just use the hread procedure directly.

Related

VHDL null file handle

I have a procedure (testbench only, non-synthesisable) which receives data via an AXIS interface and writes it to a byte array. I also want the option to write the received data to file. To do this i've added a file handle such that any test bench using this procedure can declare a file handle and pass it to the procedure and the received data will be written to the given file via the file handle.
Here's the procedure declaration:
procedure AXI_STREAM_RECEIVER
(
-- AXI-Stream Parameters
variable PAYLOAD : inout p_byte_array;
constant SLAVE_READY_BEHAVE : in t_slave_ready_behave := always_ready;
constant READY_GAP_RANGE : in natural := 20;
constant VERIFY_TKEEP : in boolean := false;
file file_handle : text;
-- Interface Clock
signal CLK : in std_logic;
-- Master/Slave I/O
signal axis_tdata : in std_logic_vector;
signal axis_tkeep : in std_logic_vector;
signal axis_tvalid : in std_logic;
signal axis_tlast : in std_logic;
signal axis_tready : out std_logic;
-- Misc.
constant VERIFY_TLAST : in boolean := true;
constant VERBOSE : in boolean := c_verbosity_default;
constant DEBUG_SEVERITY_LEVEL : in severity_level := c_axil_debug_severity_level;
constant DEBUG_PAYLOAD_CONTENT : in boolean := false
);
As I want the write to file to be optional, I was hoping to be able to provide a 'null' file handle as a default when writing to file is not required. I've tried assigning a default but I get:
FILE interface declaration must not contain a default expression
Then i've tried assigning it to 'null' when instanced:
Illegal use of NULL literal.
But then if I leave it with no default and not assigned I get:
No feasible entries for subprogram "AXI_STREAM_RECEIVER"
Anybody know if it's possible to pass in some sort of null file descriptor?
You can achieve this using a package with generics using VHDL-2008. The file handle and procedure are declared separately within the package header. Here's an example:
library ieee;
use ieee.std_logic_1164.all;
library std;
use std.textio.all;
package gen_pkg is
generic (
PRINT_TO_FILE : boolean;
FILE_NAME : string;
FILE_MODE : file_open_kind := write_mode
);
file outfile : text;
procedure TEST_PROCEDURE;
end gen_pkg;
package body gen_pkg is
procedure TEST_PROCEDURE is
variable outline : line;
begin
write(outline,string'("TEST STRING"));
if PRINT_TO_FILE then
file_open(outfile, FILE_NAME, FILE_MODE);
writeline(outfile, outline);
file_close(outfile);
end if;
end TEST_PROCEDURE;
end gen_pkg;
I've only shown a string being written, but use any of the overloaded variants of write in the textio package depending on your required datatype or you can use the VHDL-2008 function to_string which supports conversions of all types.
Then in your testbench, create a new instantiation of the package and access procedures/functions, etc. using the instantiation name:
library ieee;
use ieee.std_logic_1164.all;
library std;
use std.textio.all;
entity tb is
end tb;
architecture arch of tb is
package gp is new work.gen_pkg
generic map (
PRINT_TO_FILE => TRUE,
FILE_NAME => "./test_file.txt",
FILE_MODE => append_mode
);
begin
process begin
for i in 0 to 4 loop
gp.TEST_PROCEDURE;
end loop;
wait;
end process;
end arch;
Please note, if you write to the file more than once, like shown in this example, file mode must be append_mode. In write_mode, the file will be overwritten everytime file_open is called. If you only write to the file once per simulation, write_mode is fine. You can also have multiple new instantiations of your generic package in multiple locations, all writing to the same file, as along as they all use append_mode for the file mode.
Here's the working example on EDA playground setup to use Aldec Riviera Pro 2017.02. A login is required to run it. You must have pop-up blocker disabled in your browser in order to download the output file to inspect. The string "TEST STRING" should be written to the file 5 times.
In VHDL 2008 and earlier, you must always connect a file object in an interface list to another file object. Accessing the object when it is not open will cause an error, but there is no way to detect if the file is open or not. VHDL2019 does add a FILE_STATE function to do this, but I assume you still need to connect it to an existing file object with no defaults allowed.
Would it be easier to pass in a string of the filepath, which can have a default of ""? If it is a null string then dont open the file.

Reading text length in Vivado

I need to get the length of a text file in Vivado during simulation. I tried below piece of code but I got an error.
file my_input : TEXT open READ_MODE is "/home/sukru/MD5.dat";
variable my_line : LINE;
variable input_line : LINE;
variable length : integer;
readline(my_input, input_line);
read(input_line, length);
writeline(output, input_line); -- optional, write to std out
write(input_line, integer'(length));
writeline(output, input_line);
The error message is this.
Error: TEXTIO function READ: read a non-integer, an integer is expected
a
-2147483648
I can read text's index but the length is non-sense value. Someone direct me how can I get the length of any text file.
VHDL at present has no way of interfacing to the host operating system to determine a file length.
There's an equivalency between bytes and the VHDL type character (see IEEE Std 1076-2008).
Normative references
...
ISO/IEC 8859-1:1998, Information technology—8-bit single-byte coded graphic character sets—Part 1: Latin alphabet No. 1.
Also see 16.3 Package standard, type character where all 256 enumeration values for a single-byte character are included.
That means we can count characters in a file:
use std.textio.all;
entity length_in_bytes is
end entity;
architecture foo of length_in_bytes is
impure function file_length (file_name: string) return integer is
type char_file is file of character;
file file_in: char_file open read_mode is file_name;
variable char_buffer: character;
variable length: integer := 0;
begin
while not ENDFILE(file_in) loop
read(file_in, char_buffer);
length := length + 1;
end loop;
file_close(file_in);
-- report file_name & " length = " & integer'image(length);
return length;
end function;
signal filelength: natural;
begin
filelength <= file_length("md5.dat");
process
begin
wait for 0 ns; -- skip default signal value;
report "file md5.dat length = " & integer'image(filelength);
wait;
end process;
end architecture;
The length returned by the function call will match the length the host operating system provides.
The file_close leaves the file unlocked for further use and reads of an open file are sequential from file open.
This line reads a line from the file:
readline(my_input, input_line);
This line tries to read an integer (destructively) from the line:
read(input_line, length);
It doesn't return the length of the file (or the line). You don't supply the file you are trying to read (it would have been better had you done so - see this ), but my guess is that it doesn't contain an integer and hence your error message.
If you want to get the length of any text file, you need to read every line in the file, find each's length and add them. It is easy to find the length of each line, because type line does have a 'length attribute, so the length of each line will be:
input_line'length
(Though note that the 'length attribute does not include the end-of-line character.) By the way, this line won't display what you've just read, because the read (if successful) is destructive:
writeline(output, input_line); -- optional, write to std out
(A "destructive read" is a read which removes the data as well as reading it.)

How would I create a function to convert from an integer to std_logic vector in VHDL?

I am seeking help as I am learning this language construct.
Here is what I have:
function int_slv(val,width: integer) return std_logic_vector is
variable R: std_logic_vector(0 to width-1):=(others=>'0')
variable b:integer:= width;
begin
if (b>32) then
b=32;
else
assert 2**bits >val report
"value too big for std_logic_vector"
severity warning
end if;
for i in 0 to b-1 loop
if val ((val/(2**i)) MOD 2 = 1) then
R(i)='1';
end if;
end loop;
return(R);
end int_slv;
In addition to 5 syntax errors, one wrong identifier and a modulo reduction expressions expressed as an element of an array as well as several sets of redundant parentheses, your modified code:
library ieee;
use ieee.std_logic_1164.all;
package int2bv_pkg is
function int_slv (val, width: integer) return std_logic_vector;
end package;
package body int2bv_pkg is
function int_slv (val, width: integer) return std_logic_vector is
variable R: std_logic_vector(0 to width-1):=(others=>'0'); -- added ';'
variable b:integer:= width;
begin
if b > 32 then
b := 32; -- ":=" is used for variable assignment
else
assert 2 ** width > val report -- width not bits
"value too big for std_logic_vector"
severity warning; -- missing semicolon at the end of assertion
end if;
for i in 0 to b - 1 loop
if val/2 ** i MOD 2 = 1 then -- not val (...)
R(i) := '1'; -- ":=" variable assign.
end if;
end loop;
return R; -- parentheses not needed
end int_slv;
end package body int2bv_pkg;
analyzes (compiles). The exponentiation operator "**" is the highest priority, the division operators "/" and "mod" are the same priority and executed in the order they are found (left to right). It's likely worthwhile learning VHDL operator precedence.
You were using "=" for variable assignment when you should have been using ":=" in two places, you were missing two semicolons and were using the identifier bits (which isn't declared in your function) where apparently you meant width.
The modified example analyzes, and hasn't been tested absent a Minimal, Complete and Verifiable example in the question.
Note that a package body is a design unit as is a package declaration. There are various other places in other design units you can introduce a function body.
You could also note the 2 ** 31 is outside the guaranteed range of an integer in VHDL equal to 2147483648, while the INTEGER value range guaranteed to be from -2147483647 to +2147483647 at a minimum.
This implies that were ever you are using a value that derived from an expression equivalent to 2 ** 31 you can incur a range error during execution (either at elaboration or during simulation).
This pretty much says you need a VHDL implementation with a larger INTEGER value range or you need to rethink what you're doing.
As a matter of course there are integer to unsigned and integer to signed functions found in package numeric_std in library IEEE.
The result of such can be type converted to std_logic_vector, and the source code can make great learning aids on how to wend through the limitations VHDL imposes. These to_signed or to_unsigned functions would be capable of dealing with the maximum value an INTEGER can hold and specify the length of the resulting array type while providing zero or sign filling for array lengths greater than the INTEGER's binary value. That utility extends to clipping using length as well.
VHDL -2008 package numeric_std_unsigned contains a function To_StdLogicVector that does what your int_slv function is intended to do although limited to a NATURAL range for the integer type input.
As #user1155120 has already indicated, the VHDL-2008 package numeric_std_unsigned has a builtin to_stdlogicvector. And #user1155120 already pointed out the to_signed and to_unsigned in numeric_std are available as well.
So, to expand on the previous answer, you can do:
constant C : integer := -6817563;
constant C_VEC : std_logic_vector(31 downto 0) := std_logic_vector(to_signed(c, 32));
And this mechanism will accept the full range of integer. You can also use to_unsigned, but this is limited to the range of natural.

Is it possible to check the length of an input text file?

In my VHDL project, my input is going to be extracted from a text file containing n bits of 1's and 0's. I am trying to make it as general as possible. I am familiar with how to read and write on a text file using test-bench, but I don't know how to check its length.
My code normally takes 64 bit as input, pass them through all the blocks and generate an output. If the remaining bits length is less than 64 then it passes through a specific block.
Let's say the text file contains 1000 bits. 15 x 64 = 960. 960 bits will pass through all blocks, the remaining 40 will pass by a specific block. This looks straight forward but in order for me to do such operations i need to know the length of the text file. If anyone can help that would be very beneficial.
The VHDL data structure length should be considered, not the file length since that is implementation specific and not VHDL specified.
If the bits are in one long string that is to be chopped up into 64-bit pieces with a remainder, then the entire string can be read into a VHDL line type, and reading from that line to a std_logic_vector type can then depend on the remaining bits (characters) in the line.
Below is a code example doing so:
library ieee;
use std.textio.all;
use ieee.std_logic_textio.all; -- Synopsys package; required for VHDL-2002 only
architecture syn of tb is
begin
process is
variable myl_v : line;
file txt_file : text;
variable slv_v : std_logic_vector(63 downto 0);
begin
file_open(txt_file, "input.txt", read_mode);
readline(txt_file, myl_v);
while myl_v'length > 0 loop
if myl_v'length >= slv_v'length then -- Full slv_v
report "Full...: " & myl_v.all(1 to slv_v'length);
read(myl_v, slv_v);
else -- Reduced slv_v
report "Reduced: " & myl_v.all(1 to myl_v'length);
read(myl_v, slv_v(myl_v'length - 1 downto 0)); -- Place reduced at LSBs
end if;
end loop;
file_close(txt_file);
wait;
end process;
end architecture;
Btw, to answer the question of "length of an input text file", then the length in characters can be determined by reading as many characters from the file as possible, for example with code like:
impure function file_length_in_characters(filename : string) return natural is
type char_file_t is file of character;
file char_file : char_file_t;
variable char_v : character;
variable res_v : natural;
begin
res_v := 0;
file_open(char_file, filename, read_mode);
while not endfile(char_file) loop
read(char_file, char_v);
res_v := res_v + 1;
end loop;
file_close(char_file);
return res_v;
end function;

No function declarations for operator + error in VHDL

In this piece of code I get this error for the line with +
function func (bv1 : in bit_vector; bv2 : in integer) return bit_vector is
variable temp : natural := 2**bv2;
variable result : bit_vector(1 to 32);
begin
report "asd" & natural'image(temp);
result <= bv1 + temp; // this line causes the error
return result;
end func;
The error is :
No function declarations for operator +
How can I solve this? I also get a similar error for "=" as well.
Don't use bit_vectors (or std_logic_vectors, really) for anything you want to do arithmetic on.
Use the ieee.numeric_std library and then declare your signals (or whatever) to be of type signed ot unsigned depending on what type of vector you want. (Or of course, you can just use integers and the subtypes of that)
It's because you try to add a natural to a bit_vector which does not work because they are of different types. So you'll have to use a converter, e.g. as shown here within one of the functions. The other method is to stick to all the same types, but that isn't always possible.
Some initial problems with the code are that VHDL comments markup is --, not
//, and assign to result variable must use :=, since <= is for assign
to signal.
Then, the reason for the error:
No function declarations for operator +
is that VHDL is a strong typed language, so it is not possible just to add a
natural type and a bit_vector type, as attempted in result <= bv1 + temp.
Instead you need to use the package numeric_bit_unsigned, and for example
convert temp to bit_vector using function to_bitvector before adding.
Resulting code can then be:
library ieee;
use ieee.numeric_bit_unsigned.all;
...
function func (bv1 : in bit_vector; bv2 : in integer) return bit_vector is
variable temp : natural := 2**bv2;
variable result : bit_vector(1 to 32);
begin
report "asd" & natural'image(temp);
result := bv1 + to_bitvector(temp, result'length); -- this line causes the error
return result;
end func;
You should check that the length is enough to handle the required values.
However, instead of using bit_vector type, you may consider the
std_logic_vector (depending on the design), since the std_logic_vector has
additional values that may reveal design problem in simulation.

Resources