How to convert numerical values to string? And vice-versa? : from Redit

Hi,

someone ask that question on reddit but since the subreddit is toast i can’t read it…

I am really new to Zig and not the sharpest tool in the shed so i would appreciate if i could get some pointers on this topic.

hello

I don’t have great eloquence in English, but an example is better than a great speech

pub fn usizeToStr(v: usize ) ![]const u8{

  return std.fmt.allocPrint(dds.allocatorField,"{d}", .{v}) catch return ErrUtils.Invalide_OutOfMemory_usizeToStr;
}
2 Likes

For string to value, you’d use parseInt or parseFloat from std.fmt

const integer = fmt.parseInt(i32, "-1425"); // Interprets string as an i32 value.
const float = fmt.parseFloat(f64, "25125.1254242535"); // Interprets strings as an f64 value.

Going backwards, from an integer to a string, you could try using one of the formatInt and formatFloatDecimal functions, and configure the output and where it goes yourself, but that might require some setup, so just using allocPrint is probably better, as long as you remember to free your string later.

4 Likes

@JPL Your eloquents is good enough, thank you for your help.

So is allocPrint like sprintf? I print into a buffer with a specific format?

Take a look at the very helpful doc comment starting at line 29 (currently) of zig/lib/std/fmt.zig at master · ziglang/zig · GitHub for the details of how to specify the format when you use the various print functions in fmt. Aside from allocPrint you can also use bufPrint which doesn’t need an allocator just a writable slice to write the output to. It returns the slice of just what was written.

const std = @import("std");

pub fn main() !void {
    const n = 42;
    var buf: [256]u8 = undefined;
    const str = try std.fmt.bufPrint(&buf, "{}", .{n});
    std.debug.print("{s}\n", .{str});
}
std.fmt.allocPrint

idem sprintf
other solution

pub fn copyIntStr( n: usize )  [] const u8 {

    var buffer : [4096] u8 = undefined;
    var result =  std.fmt.bufPrintZ(buffer[0..], "{d}", .{n}) catch unreachable;
    return @as([]const u8, result);
}```

watch out for memory allocation
https://ziggit.dev/t/how-to-convert-numerical-values-to-string-and-vice-versa-from-redit/719/2

Not exactly, sprintf prints into an existing buffer, so the closest equivalent would be std.fmt.bufPrint.

allocPrint takes in an allocator and uses it to make space for the resulting string.

Careful there, you are returning a pointer to stack-allocated memory, which will disappear right after you return.

1 Like

I agree with what @gonzo said, the code as-is returns a pointer to garbage memory.

Additionally, this line has an unnecessary cast:

A mutable slice (eg []u8) will automatically coerce to the constant version (eg []const u8) without any need for an explicit cast.

2 Likes