zhangsongcui

Integer to string

Feb 12th, 2015
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. // Yet another itoa_10 implementation
  2. int int_to_string(const int32_t init_value, char* const buffer) {
  3.     char* pstart = buffer;
  4.     uint32_t value;
  5.     if (init_value < 0) {
  6.         value = -init_value;
  7.         *pstart++ = '-';
  8.     } else {
  9.         value = init_value;
  10.     }
  11.  
  12.     // INT_MAX = 2147483647
  13.     int bufneed;
  14.  
  15.     if (value >= uint32_t(1e9)) {
  16.         if (value >= uint32_t(2e9)) {
  17.             *pstart++ = '2';
  18.             value -= uint32_t(2e9);
  19.  
  20.             if (value >= uint32_t(1e8)) {
  21.                 *pstart++ = '1';
  22.                 value -= uint32_t(1e8);
  23.             } else {
  24.                 *pstart++ = '0';
  25.             }
  26.             bufneed = 8;
  27.         } else {
  28.             *pstart++ = '1';
  29.             bufneed = 9;
  30.         }
  31.     } else {
  32.         // 123456789
  33.         if (value >= uint32_t(1e4)) {
  34.             if (value >= uint32_t(1e6)) {
  35.                 if (value >= uint32_t(1e8)) {
  36.                     bufneed = 9;
  37.                 } else if (value >= uint32_t(1e7)) {
  38.                     bufneed = 8;
  39.                 } else {
  40.                     bufneed = 7;
  41.                 }
  42.             } else if (value >= uint32_t(1e5)) {
  43.                 bufneed = 6;
  44.             } else {
  45.                 bufneed = 5;
  46.             }
  47.         } else if (value >= uint32_t(1e2)) {
  48.             if (value >= uint32_t(1e3)) {
  49.                 bufneed = 4;
  50.             } else {
  51.                 bufneed = 3;
  52.             }
  53.         } else if (value >= uint32_t(1e1)) {
  54.             bufneed = 2;
  55.         } else {
  56.             pstart[0] = '0' + value;
  57.             pstart[1] = '\0';
  58.             return int(&pstart[1] - buffer);
  59.         }
  60.     }
  61.     char* pend = pstart + bufneed;
  62.     int res = int(pend - buffer);
  63.     *pend-- = '\0';
  64.     while (value > 0) {
  65.         *pend-- = '0' + value % 10;
  66.         value /= 10;
  67.     }
  68.     while (pend >= pstart) {
  69.         *pend-- = '0';
  70.     }
  71.     return res;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment