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 ++ “}”
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 . Edit: Just realized the example actually does use comptime values.comptime_int
there too (haven’t tried it)
@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});
}
placeholder in placeholder, get it.
not notice the comptimePrint. thanks a lot.