0

What is the 'standard' way to convert an std_logic_vector value into character type? It seems that first I convert it to an integer and then to character using the ASCII table. However, I am not sure how to do this in code.

Also, what is the 'standard' way to do the reverse conversion from character to std_logic_vector?

Some answers on the internet are quite old. This question is about the current form of the VHDL language and its libraries.

TonyM
  • 21,742
  • 4
  • 39
  • 62
gyuunyuu
  • 1,933
  • 7
  • 31
  • 1
    By writing your own function using a case statement. – Mitu Raj Jul 04 '22 at 18:02
  • 1
    See 5.3.2.4 Predefined operations on array types, it's a function called TO_STRING. In -2008 for other than predefined types in packages now part of the standard (std_logic_1164, numeric_std, ...) the TO_STRING functions are now declared in them. Type character is an element of various enumerated array types. TO_STRING (and it's variants) returns a string. Function call return values can be indexed. A function name is a valid prefix for a selected or a slice name. – user16145658 Jul 04 '22 at 22:58
  • Converting enumerated values to type character isn't hard. `function to_string (inp: std_logic_vector) return string is variable image_str: string (1 to inp'length); alias input_str: std_logic_vector (1 to inp'length) is inp; begin for i in input_str'range loop image_str(i) := character'VALUE(std_ulogic'IMAGE(input_str(i))); end loop; return image_str; end function;` – user16145658 Jul 04 '22 at 23:00
  • I already wrote a function that converts the std_logic_vector into an integer range 0 to 255, and then uses the character'VALUE attribute to convert it into a character. However, what you have written in the comment is a big more robust I guess. I was expecting a function that does this to exist already but I guess I was expecting too much from VHDL. – gyuunyuu Jul 04 '22 at 23:50
  • I have not yet written a function to do conversion in the other direction. I guess I will be doing it sometime soon but not right now. – gyuunyuu Jul 04 '22 at 23:51

1 Answers1

2

In terms of standard, character is an enumerated type which maps to ISO-8859-1 (i.e. ASCII for codes 0-127).

There are standard predefined attribute functions on enumerated types that can convert between enumerated value and its position in enumeration ('pos() and 'val()), then, character conversion to its 8-bit encoding is simple enough:

  subtype byte is std_ulogic_vector(7 downto 0);

  function to_byte(c : character) return byte is
  begin
    return byte(to_unsigned(character'pos(c), 8));
  end function;

  function to_character(b: byte) return character is
  begin
    return character'val(to_integer(unsigned(b)));
  end function;
Nipo
  • 1,315
  • 8
  • 9