Forgive me but I'm pretty new to Zig and need to convert an integer (e.g. i32
) into a string for display purposes. What's the idiomatic way to do this in Zig at runtime, and are there different approaches depending on the integer type or allocation needs?
In Zig, you can convert integers to strings using either bufPrint
or allocPrint
formatting functions in std.fmt
depending on your needs.
std.fmt.bufPrint
- Stack-based, no heap allocationYou can use std.fmt.bufPrint
to write the formatted integer into a fixed-size buffer.
const std = @import("std");
pub fn main() !void {
var buf: [20]u8 = undefined;
const value: i32 = -4096;
const str = try std.fmt.bufPrint(&buf, "{d}", .{value});
try std.io.getStdOut().writer().print("Result: {s}\n", .{str});
}
Notes
buf
for the outputted string to fit inside, bufPrint
will throw error.NoSpaceLeft
.{d}
specifier formats the number in decimal. You can use {x}
, {b}
, etc. for hex, binary, etc., per Zig’s formatting specifiers.std.fmt.allocPrint
- Heap allocatedAnother option is std.fmt.allocPrint
, which allocates a string on the heap and returns it. This is more flexible if you need a dynamically sized string.
const std = @import("std");
pub fn main() !void {
const allocator = std.heap.page_allocator; // You will probably want to use a different allocator
const value: u64 = 4096;
const str = try std.fmt.allocPrint(allocator, "{d}", .{value});
defer allocator.free(str);
try std.io.getStdOut().writer().print("Result: {s}\n", .{str});
}
Notes
free
the string when done, or you can inadvertently cause a memory leak.{d}
functions in allocPrint
just as it does with bufPrint
; read above for more details on it.