Converting a big integer to decimal string

后端 未结 4 780
情话喂你
情话喂你 2020-12-19 20:40

At the risk of having this question voted as a duplicate, or even to have it closed, I had this question has come up.

Background

In \"normal

4条回答
  •  暖寄归人
    2020-12-19 21:00

    Would this be the correct way?

    2nd method does not work for all integer values in C. if divisor < dividend relies on creating divisor as a power of 10 greater (or equal) than the dividend. Since most integer systems have a finite range, creating a power of 10 greater (or equal) than dividend when dividend == INTEGER_MAX is not possible. (unless INTEGER_MAX is a power of 10).


    A recursive method works by performing repeated division by 10 and deferring the the digit assignment until the more significant digits are determined. This approach works well when the size of the destination buffer is unknown, yet adequate.

    The below handles signed int and works for INT_MIN too without undefined behavior.

    // Return location of next char to write
    // Note: value is expected to be <= 0
    static char *itoa_helper(char *s, int value) {
      if (value/10) {
        s = itoa_helper(s, value/10);
      }
      *s = '0' - value % 10;  // C99
      return s+1;
    }
    
    void itoa(int n, char *s) {
      if (n < 0) {
        *s++ = '-';
      } else {
        n = -n;
      }
      *itoa_helper(s, n) = '\0';
    }
    
    #define INT_SIZEMAX  ((CHAR_BIT*sizeof(int) - 1)*28/93 + 3)
    char buf[INT_SIZEMAX];
    itoa(INT_MIN, buf);
    

    Rather than converting negative numbers to positive ones, this code does the opposite as -INT_MIN fails on most systems.

提交回复
热议问题