String to real conversion

module m();

  function void fun(string data);
   int len=data.len;
    bit [255:0]real_data[];

    real_data=new[len];
    foreach(data[i])
      begin
        real_data[i]=real '(data[i]);//---------------marked -----------
        $display("converted value of the data[%d]:%b",i,data[i]);
      end
    
 foreach(real_data[j])
      begin
        $write(":%e",real_data[j]);
      end
  endfunction
        
                
 initial begin
   fun("123");
   #10;
   fun("abc");
   #10;
   fun("2e3");
 end
endmodule

//I want to write a function which can convert any string to real values. I am getting error at the ‘marked’ line. It says index is out of array dimension bounds. $write doesn’t execute saying ‘array is empty’.
Please help how to fix it.

In reply to bhimac:

This code is not legal and should have been caught as an error. You’ve declared len as a static variable and it would only get initialized once before time 0.

See function arguments not initializing variable inside the body | Verification Academy

In reply to bhimac:

Look up atoreal() method of string. It is what you want to do, perhaps.

https://discuss.systemverilog.io/t/systemverilog-string-methods/261

In reply to dave_59:

Hi
I have edited the question again. I have mentioned some delays between each function call so that there is no problem with the len declared as static. Let me know your thoughts.

In reply to bhimac:

Hi Bhima,

Please go over Dave’s first answer and the link he has posted there.

Why do you think the delays would make any difference ? It’s not about delays or when the function is called. It’s about how you are “initializing” a function variable.

Let’s break your code to something simpler to make it easier to understand. Most modern simulators will give you an error or warning here.


module m();
 
  function void fun(int b);
   int a = b ;  // This line isn't touched every-time the function is called. It's just "initialized".
    $display("a is %0d",a);
  endfunction
 
 
 initial begin
   fun(1);  // a will be 0. it's initialized to 0, and never touched again.
   #10;
   fun(2);  // a will still be 0
   #10;
   fun(3); // a will continue to be 0.
 end
endmodule

Instead of the above, if you try the below, where to separate the initialization and the assignment, you will be fine. One of the ways to get want you want below::

module m();
 
  function void fun(int b);
   int a ;
    
    a = b; 
    $display("a is %0d",a);
  endfunction
 
 
 initial begin
   fun(1);
   #10;
   fun(2);
   #10;
   fun(3);
 end
endmodule

In reply to KillSteal:

Thank You KillSteal that was really helpful.

In reply to dave_59:

Thank You dave_59 that was really helpful.