Search code examples
arraysverilogsystem-verilog

Function to convert logic vector into string


I wrote this function to convert a logic vector into string bit by bit:

module top_2;

  function automatic string logic_to_string(logic vec []);
    string str;
    for (int i=0; i<$size(vec); i++) begin
      str = {str, (vec[i] === 1'bx) ? "x" : (vec[i] === 1'bz) ? "z" : (vec[i] ? "1" : "0")};
    end
    return str;
  endfunction

   initial begin
    logic [3:0] x;
        x = "1010";
        #1;
    $display(logic_to_string(x));
   end 

endmodule

I do not understand why I keep getting result as all zeros. What is wrong with this program? If I use (logic [] vec) instead, it does not compile.

I tried these two and they don't compile as well:

  function automatic string logic_to_string(logic vec []);
    return $sformatf("%b", vec);
  endfunction
** Error (suppressible): (vlog-2997)
top_2.sv(20): Arg. 'vec' of 'logic_to_string':  Cannot assign a packed type 'reg[3:0]' to an unpacked type 'reg $[]'

and this

  function automatic string logic_to_string(logic [] vec);
    return $sformatf("%b", vec);
  endfunction

top_2.sv(12): (vlog-13169) Packed dimension must specify a range.

At the end, I tried this one:

   initial begin
    logic [3:0] x;
    logic str;
        x = "1010";
    str = $sformatf("%b", x);
        #1;
    $display(str);
   end 
Error (suppressible): (vsim-7041)    
top_2.sv(16): String assignment:  Assigning a string to a packed type requires a cast.

Solution

  • I don't think you need to create your own function for that. You can use $sformatf with %b:

    module top_2;
        initial begin
            logic [3:0] x;
            string str;
            x = 10    ; str = $sformatf("%b", x); $display("%s", str);
            x = '1    ; str = $sformatf("%b", x); $display("%s", str);
            x = 'b1zx0; str = $sformatf("%b", x); $display("%s", str);
        end 
    endmodule
    

    Prints:

    1010
    1111
    1zx0