2018-12-25 19:09:58 +01:00
|
|
|
//----------------------------------------------------------------------------//
|
|
|
|
// GNU GPL OS/K //
|
|
|
|
// //
|
|
|
|
// Authors: spectral` //
|
|
|
|
// NeoX //
|
|
|
|
// //
|
|
|
|
// Desc: Conversion utilities //
|
|
|
|
//----------------------------------------------------------------------------//
|
|
|
|
|
2018-12-30 20:13:56 +01:00
|
|
|
#include <kaleid/common/string.h>
|
2018-12-25 19:09:58 +01:00
|
|
|
|
|
|
|
//
|
|
|
|
// 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';
|
|
|
|
}
|
|
|
|
|
2018-12-25 19:40:32 +01:00
|
|
|
// compute digits... in reverse order
|
2018-12-25 19:09:58 +01:00
|
|
|
while (i > 0) {
|
|
|
|
*str++ = digits[i % base];
|
|
|
|
i /= base;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (neg) *str++ = '-';
|
|
|
|
*str = '\0';
|
|
|
|
|
|
|
|
return reverse(orig);
|
|
|
|
}
|
|
|
|
|
|
|
|
|