Is there a way to concat comptime string and comptime_int?

i want to format a number in this way:
n: u8 = 1 → ‘01’
n: u16 = 1 → ‘0001’
n: u32 = 1 → ‘00000001’

another way, the format should be like:
“{x:0>” ++ @bitSizeOf(@TypeOf(n))/4 ++ “}”

In the following post, I mention how you can use a runtime value to fill in parts of a format specifier, but I think you can use a comptime_int there too (haven’t tried it). Edit: Just realized the example actually does use comptime values.

2 Likes

@dude_the_builder’s solution is probably better in this case.

But to also answer this part:

You also could use std.fmt.comptimePrint:

"{x:0>" ++ std.fmt.comptimePrint("{d}", .{@bitSizeOf(@TypeOf(n))/4}) ++ "}"

or escaping the brackets for the runtime format:

const std = @import("std");
pub fn main() !void {
    const n: u32 = 1;
    std.debug.print(std.fmt.comptimePrint("{{x:0>{d}}}", .{@bitSizeOf(@TypeOf(n)) / 4}), .{n});
}
2 Likes

:ok_hand: placeholder in placeholder, get it.

1 Like

not notice the comptimePrint. thanks a lot.

1 Like