Print the number in a character buffer replenished with zeros and put the string completion character always in position 6 of the buffer:
char buffer[11] = {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', 0};
int escrito = snprintf(buffer, 10, "%d", numero);
buffer[escrito] = '0';
buffer[5] = 0;
printf("%s\n", buffer);
The buffer
of the previous example has 11 characters since 10 are the maximum digits that an integer ( int
) * can have, the 11th character of the buffer is the end character of string (notice that it does not have quotes).
We print the number in the buffer, the function snprintf
returns the number of characters written, so in the last written position we return to the character '0'
(since snprintf
will have written the character ending chain ).
Finally, in position 6 (where we want to always truncate the number) we put the chain ending character.
For example, suppose we want to show the numbers 42 and 101010:
buffer | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10|
snprintf 42 |'4'|'2'| 0 |'0'|'0'|'0'|'0'|'0'|'0'|'0'| 0 |
snprintf 101010 |'1'|'0'|'1'|'0'|'1'|'0'| 0 |'0'|'0'|'0'| 0 |
When printing 42, the position 2 of the buffer is marked as end of chain (with 0
), the same happens with position 6 when printing 101010. Since in the first case we have written 2 characters and in the second 6, the buffer[escrito] = '0'
instruction leaves us the buffer like this:
buffer | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10|
42 |'4'|'2'|'0'|'0'|'0'|'0'|'0'|'0'|'0'|'0'| 0 |
101010 |'1'|'0'|'1'|'0'|'1'|'0'|'0'|'0'|'0'|'0'| 0 |
If we showed the number at that moment we would see 4200000000
and 1010100000
respectively, so we use the instruction buffer[5] = 0;
that leaves us this way the buffer:
buffer | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10|
42 |'4'|'2'|'0'|'0'|'0'| 0 |'0'|'0'|'0'|'0'| 0 |
101010 |'1'|'0'|'1'|'0'|'1'| 0 |'0'|'0'|'0'|'0'| 0 |
So showing the number at that moment we would see 42000
and 10101
respectively.
* In 32-bit architectures, the maximum number of an integer is (2 32 / 2) - 1 = 2,147,483,648