There is no standard library implementation, but for example our PoC-Libary has several formatting function in the PoC.Strings package. On top of that, we have a to_string(...)
function, which accepts a format character like h
for hexadecimal outputs.
How to write such an integer to hex conversion?
- Convert the INTEGER into a binary representation
- Group the binary value into 4-bit groups
- translate each group into an integer/alpha in range 0..F
- prepend
0x
if wished
So here is a wrapper to convert the integer to a binary representation:
-- format a natural as HEX string
function raw_format_nat_hex(Value : NATURAL) return STRING is
begin
return raw_format_slv_hex(std_logic_vector(to_unsigned(Value, log2ceil(Value+1))));
end function;
And now the grouping and transformation
-- format a std_logic_vector as HEX string
function raw_format_slv_hex(slv : STD_LOGIC_VECTOR) return STRING is
variable Value : STD_LOGIC_VECTOR(4*div_ceil(slv'length, 4) - 1 downto 0);
variable Digit : STD_LOGIC_VECTOR(3 downto 0);
variable Result : STRING(1 to div_ceil(slv'length, 4));
variable j : NATURAL;
begin
Value := resize(slv, Value'length);
j := 0;
for i in Result'reverse_range loop
Digit := Value((j * 4) + 3 downto (j * 4));
Result(i) := to_HexChar(unsigned(Digit));
j := j + 1;
end loop;
return Result;
end function;
-- convert an unsigned value(4 bit) to a HEX digit (0-F)
function to_HexChar(Value : UNSIGNED) return CHARACTER is
constant HEX : STRING := "0123456789ABCDEF";
begin
if (Value < 16) then
return HEX(to_integer(Value)+1);
else
return 'X';
end if;
end function;
-- return TRUE, if input is a power of 2
function div_ceil(a : NATURAL; b : POSITIVE) return NATURAL is -- calculates: ceil(a / b)
begin
return (a + (b - 1)) / b;
end function;
-- return log2; always rounded up
function log2ceil(arg : positive) return natural is
variable tmp : positive;
variable log : natural;
begin
if arg = 1 then return 0; end if;
tmp := 1;
log := 0;
while arg > tmp loop
tmp := tmp * 2;
log := log + 1;
end loop;
return log;
end function;
Note: These functions do not prepend 0x
.