ANSI-C: maximum number of characters printing a decimal int

前端 未结 8 1679
醉梦人生
醉梦人生 2021-02-19 10:17

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

8条回答
  •  迷失自我
    2021-02-19 10:25

    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.

提交回复
热议问题