[Libclc-developers] contribution(?): string function ultostr()
Status: Planning
Brought to you by:
augestad
|
From: Jan E. <je...@li...> - 2003-03-17 16:16:35
|
Hi,
copied this from my personal lib as I thought
this might be worth sharing, no?
/*=============================================================================
ultostr
by Jan "Hirogen2" Engelhardt <hirogen2 at gmx de>, 2003
-- distributed under the Frontier Artistic License and GNU General Public
-- License. See doc/FAL1.txt and doc/GPL2.txt for details.
-------------------------------------------------------------------------------
NAME
ultostr - convert an unsigned long integer to a string
SYNOPSIS
unsigned char *ultostr(unsigned long num, unsigned long base,
unsigned char *ptr, size_t size);
DESCRIPTION
The ultostr() function converts the number NUM to a string, in
base BASE notation. BASE must be between 2 and 36 inclusive. To
summarize it, this function does (nearly) exactly the opposite
of strtoul().
The output is written to the location pointed to by PTR, whose
length is passed in SIZE. SIZE is the number of bytes, including
space for a trailing '\0'. No more bytes than (SIZE - 1) are
written. The output is null-padded in front.
RETURN VALUE
ultostr() returns PTR on success, or NULL on error. ERANGE is
returned if BASE is < 2 or > 36. EFAULT is returned if PTR is
NULL.
EXAMPLE
unsigned char buf[12];
memset(buf, 0, 12);
printf("%s\n", ultostr(170, 2, 12));
Prints 00010101010 (11 chars).
=============================================================================*/
#include <errno.h>
#include <stdio.h>
unsigned char *ultostr(unsigned long num, unsigned long base,
unsigned char *ptr, size_t size) {
unsigned char *sym = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",
*startp = ptr + size - 2;
if(base < 2 || base > 36) { errno = ERANGE; return NULL; }
if(ptr == NULL) { errno = EFAULT; return NULL; }
while(--size > 0) {
*ptr = sym[num % base];
num /= base;
--ptr;
}
return ptr;
}
//==[ End of file ]============================================================
- Jan Engelhardt
|