verilogsystem-verilog

A function that transforms an integer into a string so that it fits in a designated number of positions and then outputs it


I have been using VHDL for a while and am used to the to_string and integer'image functions within it. I am trying to write some SystemVerilog and just realized that the string concatenation and especially integer to string works differently.

I am trying to write a to_string function for integer in SystemVerilog. It shall take three parameters. The first is the integer to be converted (obviously). The second is the number of places that it's string representation must take. This could be in the form of 0s or in the form of spaces so the third parameter shall be the padding character.

I am not sure how to tell the $sformat function that the amount of padding is supposed to be variable and also specify the padding character. Is writing a low level function with byte level string manipulation the only way to do this?

Convert 12 to string to fit in 5 places, pad with zeros and not empty space. This gives:

00012

Solution

  • This should get you started. It leverages this technique to build a format string.

    module tb;
    
    string str;
    
    function string to_str (int num, width);
        string fmt;
        // %%  is a literal %
        // 0   is the pad character
        // %0d formats the width as an integer with no padding
        // d   is for digit
        fmt = $sformatf("%%0%0dd", width);
        return $sformatf(fmt, num);
    endfunction
    
    initial begin
        str = to_str(12, 4) ; $display(str);
        str = to_str(12, 5) ; $display(str);
        str = to_str(12, 6) ; $display(str);
        str = to_str(123, 7); $display(str);
        str = to_str(123, 8); $display(str);
        str = to_str(123, 9); $display(str);
    end
    
    endmodule
    

    Prints:

    0012
    00012
    000012
    0000123
    00000123
    000000123