53 lines
1.3 KiB
C
53 lines
1.3 KiB
C
//----------------------------------------------------------------------------//
|
|
// GNU GPL OS/K //
|
|
// //
|
|
// Authors: spectral` //
|
|
// NeoX //
|
|
// //
|
|
// Desc: Conversion utilities //
|
|
//----------------------------------------------------------------------------//
|
|
|
|
#include <kaleid/common/string.h>
|
|
|
|
//
|
|
// Digits table for bases <=36
|
|
//
|
|
static const char digits[36] =
|
|
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
|
|
//
|
|
// Integer to string in any base between 2 and 36 (included)
|
|
//
|
|
char *itoa(int i, char *str, int base)
|
|
{
|
|
int neg = 0;
|
|
char *orig = str;
|
|
|
|
if (base < 2 || base > 36)
|
|
return NULL;
|
|
|
|
// deal with negatives
|
|
if (i < 0) {
|
|
neg = 1;
|
|
i = -i;
|
|
}
|
|
|
|
// deal with zero separatly
|
|
if (i == 0) {
|
|
*str++ = '0';
|
|
}
|
|
|
|
// compute digits... in reverse order
|
|
while (i > 0) {
|
|
*str++ = digits[i % base];
|
|
i /= base;
|
|
}
|
|
|
|
if (neg) *str++ = '-';
|
|
*str = '\0';
|
|
|
|
return reverse(orig);
|
|
}
|
|
|
|
|