Why does this print "1"

Why does this print “1” instead of a a bunch of zeros, and a ‘1’?

const std = @import("std");

pub fn main() void {
    std.debug.print("binary {b}", .{ @as(u32, 1)});
}

The default is to print without leading zeroes. You need to change the format specifier.

5 Likes

Note you can confirm this behavior by checking the source code, the actual printing of the digits comes from std.Writer.printIntAny

Which does:

while (true) {
    const digit = a % base;
    index -= 1;
    buf[index] = std.fmt.digitToChar(@intCast(digit),base);
    a /= base;
    if (a == 0) break;
}
1 Like

I find it “weird” if I have binary, that it doesn’t automatically use the actual digits that the integer has. But, thanks for the quick response.

Is there a reason it behaves like that? I’m trying to understand the “why”, mora than critique the function itself

I think this behavior is reasonable. the decimal output also doesn’t pad with leading zeroes :smiley: and if you want leading zeroes there is a way to get it with a format specifier whereas if the default was to add leading zeroes then there is no format specifier to remove those zeroes

3 Likes

Ok, I understand the last part of not being able to specify that leading zeros should not be printed, instead of the opposite (and exactly how many). But the decimal comparison seems odd, since ‘b’ has a known and finite number of digits in the actual type of what is being printed, unlike decimal.

I don’t know why was I expecting it to print the leading zeros, but I understand that the expectation was overly high now. Thanks

1 Like

Octal and hexadecimal also have a defined number of digits for binary number. However, they are usually not printed with leading zeroes unless you specifically want to point out the width of the underlying type

3 Likes

I value more the consistent behavior in this case, across different bases (10, 8, 2, 16).

3 Likes

Btw, if you want to, you can specify that you want 0 padding:

std.debug.print("binary {b:0>32}\n", .{@as(u32, 1)});

To be pedantic, decimal does have a known and finite number of digits for a given bit width. All positive integer number bases do.

4 Likes

You just need a logarithm, but absolutely yes :slight_smile: