I have a VHDL testbench where I would like to write 32-bit binary words to a file for testing. Below is a minimal, complete, verifiable example.
When executed with GHDL (commands below) an overflow is generated at the indicated line. If the line is commented out execution completes successfully and writes the file. The overflow occurs anytime the high bit is set.
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use std.textio.all;
use std.env.stop;
entity u32_file_write is
end entity;
architecture rtl of u32_file_write is
type intFileType is file of natural;
file fh : intFileType;
begin
run: process
variable no_high_bit : std_logic_vector(31 downto 0) := x"7FFFFFFF";
variable with_high_bit : std_logic_vector(31 downto 0) := x"FFFFFFFF";
begin
file_open(fh, "out.bin", write_mode);
write(fh, to_integer(unsigned(no_high_bit)));
write(fh, to_integer(unsigned(with_high_bit))); -- Overflow here.
file_close(fh);
stop;
end process;
end architecture;
I run the following GHDL commands to run the VHDL code (save as u32_file_write.vhd
):
ghdl -a -fexplicit --std=08 --ieee=synopsys u32_file_write.vhd
ghdl -e -fexplicit --std=08 --ieee=synopsys u32_file_write
ghdl -r -fexplicit --std=08 --ieee=synopsys u32_file_write
With the line commented out, the corrected results are written to the file:
% od -tx4 out.bin
0000000 7fffffff
If the line is uncommented, an overflow is generated:
ghdl:error: overflow detected
from: ieee.numeric_std.to_integer at numeric_std-body.vhdl:3040
ghdl:error: simulation failed
As noted above, the write will work with any value in the first 31-bits. The write will overflow with any value where the 32-bit is set.
The underlying problem is integer'high is 2^31-1. See:
The accepted answer here states to use an intermediate 'text' format a text processing language. Another answer shows a solution for reading using 'pos but that doesn't help me write.
Is there a simple rework/workaround that will allow me to write all 32-bits of data to a binary file?