Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

26
Dec

Unsigned long to string (ultostr)

Related Blog Items

Here is the code snippet which does conversion from unsigned long to string/ascii. There are library functions exists (ltostr, itoa) to integer to ascii, but there is no library function exists for unsigned long to ascii/string. ltostr converts signed long to string/ascii.

 

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);
}

examples of usage of this function:

char ptr[1024];

ultostr(0xf34C5, ptr, 16);
output: "F34C5"

ultostr(0xf34C5, ptr, 10);
output: "996549"

ultostr(07624, ptr, 8);
output: "7624"

ultostr(07624, ptr, 10);
output: "3988"

download unsigned long to string/ascii/char * (ultostr) [ultostr.c].

Popularity: 23%

You need to log on to convert this article into PDF


Related Blog Items

1 Comment

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image