Source for "integer to ascii" and multiple file search-n-replace
Alan M. Carroll
carroll at cs.uiuc.edu
Wed Nov 21 02:35:49 AEST 1990
sprintf() is often times inadequate, or too bulky. This code will convert from
a long to any base 2..36.
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
char *
UnsignedLongToString(n,base)
unsigned long n;
unsigned int base;
{
char *digit = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static char LongToStringBuffer[34]; /* 32+nul+negative sign */
char *s = LongToStringBuffer + 33; /* at most 33 characters in binary */
*s = 0; /* terminate */
while (n) /* something there */
{
*--s = digit[n % base]; /* store bottom digit */
n /= base; /* shift right */
}
if (*s == 0) *--s = '0'; /* in case nothing was put in string */
return s;
}
char *
LongToString(n,base)
long n;
int base;
{
char *s;
if (n < 0)
{
s = UnsignedLongToString((unsigned long) -n, base);
*--s = '-';
}
else s = UnsignedLongToString((unsigned long) n, base);
return s;
}
/* ------------------------------------------------------------------------ */
main()
{
printf("%s\n",LongToString(-1234567,10));
printf("%s\n",UnsignedLongToString(7654321,10));
printf("%s\n",LongToString(0x12345,16));
}
--
Alan M. Carroll Barbara/Marilyn in '92 :
Epoch Development Team + This time, why not choose the better halves?
CS Grad / U of Ill @ Urbana ...{ucbvax,pur-ee,convex}!cs.uiuc.edu!carroll
More information about the Comp.lang.c
mailing list