How can I convert an integer to a string in Zig?

Asked about 2 months ago Viewed 14 times

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?

1
J
J Early User
109
1 Answer
Sort by
Posted about 2 months ago Modified about 2 months ago

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 allocation

You 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

  • If you don't allocate enough space in buf for the outputted string to fit inside, bufPrint will throw error.NoSpaceLeft.
  • The {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 allocated

Another 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

  • You must 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.
0
w
79

Your Answer

You Must Log In or Sign Up to Answer Questions