Golang formating of alternate form with zero padding

202 views
Skip to first unread message

Lukas Toral

unread,
Jan 31, 2024, 8:23:01 AM1/31/24
to golang-nuts
Hello,

I am working on code that formats strings. I have an issue with formatting the alternate form with zero padding of signed hexadecimals.

I have a format string like this: "%#07x", I would expect the zero padding to make sure the total width is 7. However, when I format the string using fmt.Sprintf I get the following results: 0x000002a which has the length of 9 characters instead of the expected result: 0x0002a with the width of 7 characters.

Example code: x := fmt.Sprintf("%#07x", 42) 
x will be equal to: 0x000002a

Example of python code that works as I would expect: result = "{:#07x}".format(42)
results will be equal to: 0x0002a

I am suspicious that this might be a bug where the 0x is not accounted in the width but maybe I am doing something wrong.
Thanks for any help :)

Brian Candler

unread,
Jan 31, 2024, 8:56:07 AM1/31/24
to golang-nuts

The '#' means you want the alternate format with the 0x prepended, and the '7' means you want the number itself padded to 7 digits 

x := fmt.Sprintf("%07x", 42)   // 000002a
y := fmt.Sprintf("%0#7x", 42)   // 0x000002a
z := fmt.Sprintf("0x%07x", 42)   // 0x000002a

Seems pretty logical to me. If Python chooses to do it a different way, that's because Python is a different language.

Brian Candler

unread,
Feb 3, 2024, 4:08:51 PM2/3/24
to golang-nuts
Admittedly, C and Python work the same way, which is different to Go.

#include <stdio.h>

int main(void) {
    printf("%07x\n", 42);
    printf("%0#7x\n", 42);
    printf("0x%07x\n", 42);
    return 0;
}

// Output
000002a
0x0002a
0x000002a
Reply all
Reply to author
Forward
0 new messages