Assigning a packed type 'byte' to a string requires a cast

Hello,

I am struggling with a compilation error about the following task which is meant to convert every character of a given string into their ASCII equivalent:

task StoH(input string str_in, output logic [4096] hex_out);
begin 

static int i=0;

while(str_in[i]!="\0")
begin
CtoH(str_in[i],hbyte);
temp = ~(~hbyte<<(8*i));
hex_out|=8'hFF<<(8*i);
i++;
end
end
endtask

endtask

task CtoH(input string char_in, output logic [7:0] hex_out);
begin

case (char_in)
"A" : hex_out = 8'h41;
"B" : hex_out = 8'h42;
[...]
"Z" : hex_out = 8'h5A;

endcase

end
endtask

The error triggers when I call CtoH in StoH… any idea of what I am doing wrong?

Also, any idea on how to make hex_out a more ‘flexible’ size instead of a hardcoded one?

Many thanks in advance!

In reply to CLMdB:

A select of a string type str_in[i] is not a string, it is a byte. Change the CtoH argument to

input byte char_in

You could also use a dynamic array of bytes to store your string. Then use a bit-stream cast to convert the string type to an array of bytes type.

typedef byte unsigned bytes[];

function void StoH(input string str_in, output bytes hex_out);
  hex_out = bytes'(str_in);
endfunction

module top;
  
  string str = "ABCD";
  bytes  bs;
  
  initial begin
    StoH(str,bs);
    foreach(bs[i]) $displayh(bs[i]);
  end
endmodule

Note using functions instead of tasks for procedures that do not consume time.