How to convert unsigned long to string

后端 未结 6 1892
[愿得一人]
[愿得一人] 2020-12-08 03:14

In the C language, how do I convert unsigned long value to a string (char *) and keep my source code portable or just recompile it to work

6条回答
  •  春和景丽
    2020-12-08 03:24

    you can write a function which converts from unsigned long to str, similar to ltostr library function.

    char *ultostr(unsigned long value, char *ptr, int base)
    {
      unsigned long t = 0, res = 0;
      unsigned long tmp = value;
      int count = 0;
    
      if (NULL == ptr)
      {
        return NULL;
      }
    
      if (tmp == 0)
      {
        count++;
      }
    
      while(tmp > 0)
      {
        tmp = tmp/base;
        count++;
      }
    
      ptr += count;
    
      *ptr = '\0';
    
      do
      {
        res = value - base * (t = value / base);
        if (res < 10)
        {
          * -- ptr = '0' + res;
        }
        else if ((res >= 10) && (res < 16))
        {
            * --ptr = 'A' - 10 + res;
        }
      } while ((value = t) != 0);
    
      return(ptr);
    }
    

    you can refer to my blog here which explains implementation and usage with example.

提交回复
热议问题