How to parse an integer from a string in Zig?

Asked 6 days ago Viewed 33 times

What is the proper way to parse an integer from a string in Zig, while being able to specify the resulting integer type?

const foo = "96";

How would I convert foo to an i32, for example?

3
J
J
99
1 Answer
Sort by
Accepted by Author Posted 6 days ago Modified 5 days ago

std.fmt.parseInt from the standard library is what you are looking for. It allows parsing integers of various types (u32, i64, u8, etc.), as well as bases (binary, hexadecimal, etc.).

Example:

const foo = "96";

const foo_integer = try std.fmt.parseInt(i32, foo, 10);

Inputting a value of 0 for the base allows parseInt to auto-detect the base for you based on prefixes.

  • Prefix of 0b - Base 2 (Binary)
  • Prefix of 0o - Base 8 (Octal)
  • Prefix of 0x - Base 16 (Hexadecimal)

Another thing to note is that underscores (_) are safely ignored in the input string and will not throw a parse error.

You may also want to look at std.fmt.parseUnsigned if you expect only unsigned integers, it functions very similarly.

4
s
56

Your Answer

You Must Log In or Sign Up to Answer Questions