LoginSignup
4
3

More than 1 year has passed since last update.

System Verilogでの数値<=>文字列変換まとめ

Last updated at Posted at 2019-10-13

シミュレーションしてデータをファイルダンプする際にファイル名に連番で番号振ったり、逆に連番で名前の付いたファイルを順番に読み込みたいなど数値=>文字列の変換をしたい機会が結構あると思う。また、同様に文字列=>数値変換をしたい場合もあると思う。なので以下、System Verilogでの数値<=>文字列変換の方法をまとめてみたので参考にされたし。

数値=>文字列変換

1の$sformatf()が一番お手軽だと思う。これが使えない場合は他を考えれば良いと思う。

1 $sformatf()で文字列出力

$sformatf()
for(int i=0; i<10; i++)
  $display("%s", $sformatf("%d", i));  

$sformatf()String Format Functionの意味。functionなので返り値があり、formatされたstringを返す。
因みに返り値が無いtaskバージョンは$sformat(<string>, <format>, <argument list>)(String Format)。返り値が無いので引数にフォーマット後のstringを指定する。

2 stringのitoa()を使用

itoa()
string str;
for(int i=0; i<10; i++) begin
  str.itoa(i);
  $display("%s", str);
end

3 ASCIIコードで処理

ascii_code
byte code0 = "0";
for(int i=0; i<10; i++)
  $display("%c", code0 + i);

文字列=>数値変換

こちらは2のstringのatoi()が簡単なんじゃないかと思う。

1 $sscanf()で整数読み取り

$scanf()
string number[10] = '{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
int val;
for(int i=0; i<10; i++) begin
  $sscanf(number[i], "%d", val);
  $display("%d", val);
end

$sscanf()String Scan Functionの意味。
因みにstringからではなくファイルから読み取るバージョンは$fscanf()(File Scan Function)。これとか参照。

2 stringのatoi()を使用

atoi()
string number[10] = '{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
for(int i=0; i<10; i++)
  $display("%d", number[i].atoi());

3 ASCIIコードで処理

ascii_ccode
byte code[10] = '{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
for(int i=0; i<10; i++)
  $display("%d", code[i] - "0");
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3