Prefix bufPrint single digit hex values with 0?

I am passing some colors over to javascript, and whilst trying to debug why I always get the same colors for different values of ‘d’, I created a small test and discovered another problem. How do I get a prefix of ‘0’ on single digit hex strings?

eg:

Color: [#444]

ideally should be:

Color: [#040404]

I was expecting this to work as the format string:

"#{0X}{0X}{0X}"

but no joy, and using a width specifier of 2 just inserts a space.

Here is the code (sorry for poor quality, 1st week of Zig)

const std = @import("std");
const stdout = std.io.getStdOut().writer();
const bufPrint = std.fmt.bufPrint;

const maxStarDistance: f32 = 60;

pub fn main() anyerror!void {
    const d: f32 = 59;
    var b: [8]u8 = undefined;
    const ratio: u8 = @floatToInt(u8, (255.0 - ((d / maxStarDistance) * 255.0)));
    const color = bufPrint(b[0..], "#{X}{X}{X}", .{ ratio, ratio, ratio }) catch unreachable;
    var x = [_:0]u8{0} ** 7;
    for (color) |c, i| {
        x[i] = c;
    }
    try stdout.print("Color: [{s}]\n", .{x[0..:0]});
}

PS the funny buffer/color [] conversion is because it gets passed over an ‘extern’ method into javascript. ie I needed type:

[*:0]const u8

I think this is what you’re looking for:

const std = @import("std");

pub fn main() !void {
    std.debug.print("{X:0>2}", .{4});
}
1 Like

@kristoff’s answer will work, or in your case, since you are formatting a slice, you could try std.fmt.fmtSliceHexUpper:

const std = @import("std");

pub fn main() !void {
    const x = [_]u8{ 3, 4, 5 };
    std.debug.print("#{s}\n", .{std.fmt.fmtSliceHexUpper(&x)});
}

which will print
#030405

1 Like

Thanks to you both for the answers, I currently have infrequent internet access, so if there is any other offline documentation I could be learning from, that would be much appreciated. I was trying to work it out from the source but not getting far :slight_smile: I will create a separate topic for the c-string issue.