I\'d like to know if it is an easy way of determining the maximum number of characters to print a decimal int
.
I know
contains
You can calculate the number of digits using log base 10. In my system, calculating the ceiling of log base 2 using the bit representation of the number didn't provide any significant gain in speed. The floor of log base 10 + 1 gives the number of digits, I add 2 to account for the null character and sign.
#include
#include
#include
int main(void){
printf("%d %d\n", INT_MAX, (int)floor(log10(INT_MAX)) + 3);
return 0;
}
Also note that the number of bytes of an int
can be 2 or 4 and it is 2 only in old systems, so you could calculate the upper bound and use it in your program.