Faster uint to char* conversion

The function implemented below can be used to replace something like:

unsigned int val = 45;
char aux[20];
sprintf(aux, "%u", val);

to

unsigned int val = 45;
char aux[20];
uint_to_char(aux, val);

And it performs far better. Clearly, the function is designed to perform its specific task without the need to handle all the parsing and additional operations that the printf family of functions requires.

void uint_to_char(char* a, unsigned int n)
{
  if (n == 0)
  {
    *a = '0';
    *(a+1) = '\0';
    return;
  }
     
  char aux[20];
  aux[19] = '\0';
  char* auxp = aux + 19;
     
  int c = 1; 
  while (n != 0)
  {
    int mod = n % 10;
    *(--auxp) = mod | 0x30;
    n /=  10;
    c++;
  }
     
  memcpy(a, auxp, c);
}

One thought on “Faster uint to char* conversion

  1. memcpy(a, auxp, 20-((size_t)auxp-(size_t)aux));
    no need for c variable…

Leave a reply to ardanew Cancel reply