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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With