Formatting Data to a String in Verilog and SystemVerilog

In this article, we’re going to dive into some neat Verilog and SystemVerilog functionalities that allow us to format data into strings. We’ll be exploring $swrite, $sformat, and $sformatf. If you're like me, you've probably found yourself needing to convert data into strings for logging, debugging, or even just displaying results in a readable format. Well, these three tasks are perfect for that.

$swrite System Task

Let's start with $swrite. It's quite similar to $fwrite, but instead of writing to a file, it writes to a string variable. This can be incredibly useful when you want to manipulate the string further within your code.

Example

Here's a simple example to illustrate $swrite:

module ExampleSwrite;
  string my_str;
  int a = 5;
  real b = 3.14;

  initial begin
    $swrite(my_str, "Integer: %0d, Real: %0.2f", a, b);
    $display("Formatted String: %s", my_str);
  end
endmodule

In this example, my_str is our target string variable. We format the string to include the integer a and the real number b, then display it. Easy, right?

$sformat System Task

Next up is $sformat. It's a bit more flexible because it allows the format string to be a variable or an expression. This means you can build your format string dynamically if needed.

Example

Let's see $sformat in action:

module ExampleSformat;
  string my_str;
  int a = 10;
  string format_str = "The value of a is: %0d";

  initial begin
    $sformat(my_str, format_str, a);
    $display("Formatted String: %s", my_str);
  end
endmodule

In this case, we define format_str separately and use it in $sformat. The output will still be the same, but this method gives us more flexibility.

$sformatf System Function

Finally, there's $sformatf, which is almost identical to $sformat but operates as a function. Instead of assigning the formatted string to a variable, it returns the string directly.

Example

Here's an example of $sformatf:

module ExampleSformatf;
  string result;
  int a = 42;
  real b = 2.718;

  initial begin
    result = $sformatf("Answer: %0d, Euler's number: %0.3f", a, b);
    $display("Formatted String: %s", result);
  end
endmodule

With $sformatf, the formatted string is returned directly and can be assigned to result.


I hope this gives you a clear understanding of how to use these formatting functions in SystemVerilog. They each have their own niche uses and can make handling strings much more straightforward and flexible.