VLSI DV Interview Puzzles · All levels
String Number Parsing Stops Early
What values do `atoi` and `atohex` return here?
Puzzle
Difficulty: Medium · Puzzle 6 of 6 · Topic: String and Casting Puzzles
What values do `atoi` and `atohex` return here?
Code
systemverilog
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
endmoduleHint
`atoi` reads decimal digits from start and stops at first non-digit. `atohex` interprets hex digits.
Step-by-step solution
diagram
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
Answer: d1=1234, d2=12, h1=31
Why candidates get it wrong
Interviewees often assume parse fails completely when non-digit appears mid-string.
Interviewer follow-up
What does `"x123".atoi()` return, and why?