Source code in embedded C for unsigned integer to string

前端 未结 6 1947
离开以前
离开以前 2020-12-18 14:42

Without resorting to standard library utoa, I\'m looking for source code of utoa so I may customise it for specific project. I have unsigned integer (32 bits) with output su

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-18 15:10

    That's not terribly hard. Keep dividing by 10 and use the remainder mod 10 as an index into "0123455679". You build this up from right to left, so you have to buffer the result and return it in reverse:

    char * utoa(unsigned int n)
    {
      char * res, buf[30]; // long enough for largest number
      unsigned int i, counter = 0;
    
      if (n == 0)
        buf[counter++] = '0';
    
      for ( ; n; n /= 10)
        buf[counter++] = "0123456789"[n%10];
    
      res = malloc(counter);
    
      for (i = 0; i < counter; ++i)
        res[i] = buf[counter - i - 1];
    
      return res;
    }
    

提交回复
热议问题