2018-12-25 19:09:58 +01:00
|
|
|
//----------------------------------------------------------------------------//
|
|
|
|
// GNU GPL OS/K //
|
|
|
|
// //
|
|
|
|
// Authors: spectral` //
|
|
|
|
// NeoX //
|
|
|
|
// //
|
|
|
|
// Desc: Conversion utilities //
|
|
|
|
//----------------------------------------------------------------------------//
|
|
|
|
|
2019-01-01 13:09:57 +01:00
|
|
|
#include <kaleid.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)
|
|
|
|
//
|
2019-01-01 17:37:58 +01:00
|
|
|
#if defined(_NEED_ITOA)
|
2018-12-25 19:09:58 +01:00
|
|
|
char *itoa(int i, char *str, int base)
|
2019-01-01 17:37:58 +01:00
|
|
|
#elif defined(_NEED_LTOA)
|
|
|
|
char *ltoa(long i, char *str, int base)
|
|
|
|
#elif defined(_NEED_UTOA)
|
|
|
|
char *utoa(uint i, char *str, int base)
|
|
|
|
#elif defined(_NEED_ULTOA)
|
|
|
|
char *ultoa(ulong i, char *str, int base)
|
|
|
|
#else
|
|
|
|
#error "What am I supposed to declare?"
|
|
|
|
#endif
|
2018-12-25 19:09:58 +01:00
|
|
|
{
|
2019-01-01 17:37:58 +01:00
|
|
|
#if defined(_NEED_ITOA) || defined(_NEED_LTOA)
|
2018-12-25 19:09:58 +01:00
|
|
|
int neg = 0;
|
2019-01-01 17:37:58 +01:00
|
|
|
#endif
|
|
|
|
|
2018-12-25 19:09:58 +01:00
|
|
|
char *orig = str;
|
|
|
|
|
|
|
|
if (base < 2 || base > 36)
|
|
|
|
return NULL;
|
2019-01-01 17:37:58 +01:00
|
|
|
|
|
|
|
#if defined(_NEED_ITOA) || defined(_NEED_LTOA)
|
2018-12-25 19:09:58 +01:00
|
|
|
// deal with negatives
|
|
|
|
if (i < 0) {
|
|
|
|
neg = 1;
|
|
|
|
i = -i;
|
|
|
|
}
|
2019-01-01 17:37:58 +01:00
|
|
|
#endif
|
2018-12-25 19:09:58 +01:00
|
|
|
|
2019-01-01 17:37:58 +01:00
|
|
|
// deal with zero separately
|
2018-12-25 19:09:58 +01:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2019-01-01 17:37:58 +01:00
|
|
|
#if defined(_NEED_ITOA) || defined(_NEED_LTOA)
|
2018-12-25 19:09:58 +01:00
|
|
|
if (neg) *str++ = '-';
|
2019-01-01 17:37:58 +01:00
|
|
|
#endif
|
|
|
|
|
2018-12-25 19:09:58 +01:00
|
|
|
*str = '\0';
|
|
|
|
|
|
|
|
return reverse(orig);
|
|
|
|
}
|
|
|
|
|
|
|
|
|