Difficulty: Easy · Puzzle 6 of 6 · Topic: String and Casting Puzzles
What values do `atoi` and `atohex` return here?
module p6;
string s1 = "1234";
string s2 = "12x3";
string s3 = "1f";
int d1, d2, h1;
initial begin
d1 = s1.atoi();
d2 = s2.atoi();
h1 = s3.atohex();
$display("d1=%0d d2=%0d h1=%0d", d1, d2, h1);
end
endmodule`atoi` reads decimal digits from start and stops at first non-digit. `atohex` interprets hex digits.
1) `"1234".atoi()` consumes all digits -> 1234.
2) `"12x3".atoi()` stops at `x`, so value is 12.
3) `"1f".atohex()` parses as hex 0x1F -> 31.Answer: d1=1234, d2=12, h1=31
Checked by running the code in Icarus Verilog 13 and Verilator 5; the printed output supports the answer above. atoi stops at the first non-digit. (Icarus, 4-state) atoi stops at the first non-digit. (Verilator, 2-state)
`atoi` stops at the first non-digit and keeps the digits read so far ("12x3" gives 12, not 0), and "1f" through `atohex` is 31, not 15.
What does `"x123".atoi()` return, and why? Model answer: 0, because the first character is not a digit so no digits are read before the scan stops.
I would say that atoi reads digits until the first non-digit and keeps what it already read. So 1234 gives 1234, and 12x3 gives 12, not 0. The hex version reads 1f as 31. The trap is expecting an error or 0 on bad input, or reading 1f as decimal. I would check that the string is clean before converting it.