Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf leading zero padding in C

Tags:

c

printf

The code below prints ffffffffff.

I need to the output to be 16 digits long 000000ffffffffff with leading zeros. The var1 and var2 variables can be different so it is not necessary that I want to pad 6 zeros only. I just need to output to be 16 digits with leading zeros. How should I proceed?

#include <stdio.h>

int main() {
    int var1 = 1048575;
    int var2 = 1048575;

    char buffer[100];

    sprintf(buffer, "%x%x", var1, var2);
    printf("%s\n", buffer);

    return 0;
}
like image 467
PI314159 Avatar asked Jul 17 '26 07:07

PI314159


1 Answers

You could do it in two steps:

#include <stdio.h>

int main(void) {
    int var1 = 1048575;
    int var2 = 1048575;
    int length = 0;
    char buffer[100];
    char paddedbuffer[100] = "000000000000000";
    length = sprintf (buffer, "%x%x", var1, var2);
    char* here = length < 16 ? paddedbuffer + 16 - length : paddedbuffer;
    sprintf(here, "%s", buffer);
    printf("%s\n", paddedbuffer);
    return 0;
}

There's probably a more elegant solution somewhere.

Another possibility is converting your result into an integer and sprintfing that with a field width, or calculating the actual digits of the rightmost number first.

like image 197
molbdnilo Avatar answered Jul 19 '26 20:07

molbdnilo