String concatenation and/or ternary operator behaves weirdly wit $fwrite

$fwrite(file_handle, {i != 0 ? “a” : “b”, “%h”}, number);

where file_handle is a file handle and number is a number.

results in a sequence of numbers that I cannot make sense of and does not seem related to the number put into the format modifier.

$fwrite(file_handle, i != 0 ? “a” : “b”);
outputs 98, which is the ascii value of b

what is the reason for this behaviour?

In reply to xning:

What are you expecting to see?

In reply to dave_59:

Sorry for the late reply.

For $fwrite(file_handle, {i != 0 ? “a” : “b”, “%h”}, number);
I expect it to write a or b, depending on the result of the comparison i!=0 followed by number formatted in hexadecimal.

To be more concrete,

$fwrite(f, {“”,“%h”}, 20);
→ " 9576 20"

$fwrite(f, 0!=0 ? “”:“%h”, 20);
→ " 9576 20"

$fwrite(f, “%h”, 20);
→ 00000014

this is what happens, where I would expect every scenario to produce the last output.

Is there some interaction with the concatenation and ternary op here I do not know?

In reply to xning:

The problem here is that only string literals get interpreted as a format specifier for write/display tasks

If you try

$display("%h %d",{"","%h"}, 20);

This prints out 002568 20 because
00 hex is the null string “”
25 hex is ASCII for %
68 hex is ASCII for h

002568 hex is 9576 decimal.

Only $sformat and $sformatf accept format_specifiers that are not string literals. You can try

$fwrite(file_handle, "%s", $sformatf{i != 0 ? "a" : "b", "%h"}, number) );