C: 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];
uinttochar(aux, val);

And performs far better. Obviously, my function simply performs its task and does not need to do all parsing and extra tasks that the printf family does.

void uinttochar(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);
}
Advertisements

One thought on “C: Faster uint to char* conversion

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s