1
0
mirror of https://gitlab.os-k.eu/os-k-team/os-k.git synced 2023-08-25 14:03:10 +02:00
os-k/kaleid/common/itoa.c
2019-01-14 14:31:49 +01:00

82 lines
1.9 KiB
C

//----------------------------------------------------------------------------//
// GNU GPL OS/K //
// //
// Authors: spectral` //
// NeoX //
// //
// Desc: Conversion utilities - itoa family //
//----------------------------------------------------------------------------//
#include <kaleid.h>
//
// Digits table for bases <=36
//
static const char digits[] =
"0123456789abcdefghijklmnopqrstuvwxyz";
//
// Integer to string in any base between 2 and 36 (included)
//
#if defined(_NEED_ITOA)
char *itoa(int i, char *str, int base)
#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
{
#if defined(_NEED_ITOA) || defined(_NEED_LTOA)
int neg = 0;
#endif
char *orig = str;
//
// Only handle base 2 -> 36
//
if (base < 2 || base > 36)
return NULL;
#if defined(_NEED_ITOA) || defined(_NEED_LTOA)
//
// Deal with negatives
//
if (i < 0) {
neg = 1;
i = -i;
}
#endif
//
// Deal with zero separately
//
if (i == 0) {
*str++ = '0';
}
//
// Compute digits... in reverse order
//
while (i > 0) {
*str++ = digits[i % base];
i /= base;
}
#if defined(_NEED_ITOA) || defined(_NEED_LTOA)
if (neg) *str++ = '-';
#endif
*str = '\0';
//
// Reverse the string
//
return strrev2(orig);
}