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

82 lines
1.9 KiB
C
Raw Normal View History

2018-12-25 19:09:58 +01:00
//----------------------------------------------------------------------------//
// GNU GPL OS/K //
// //
// Authors: spectral` //
// NeoX //
// //
2019-01-02 17:19:13 +01:00
// Desc: Conversion utilities - itoa family //
2018-12-25 19:09:58 +01:00
//----------------------------------------------------------------------------//
2019-01-01 13:09:57 +01:00
#include <kaleid.h>
2018-12-25 19:09:58 +01:00
//
2019-01-14 14:31:49 +01:00
// Digits table for bases <=36
2018-12-25 19:09:58 +01:00
//
2019-01-14 14:31:49 +01:00
static const char digits[] =
"0123456789abcdefghijklmnopqrstuvwxyz";
2018-12-25 19:09:58 +01:00
//
2019-01-14 14:31:49 +01:00
// Integer to string in any base between 2 and 36 (included)
2018-12-25 19:09:58 +01:00
//
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
2019-01-14 14:31:49 +01:00
#error "What am I supposed to declare?"
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
#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;
2019-01-14 14:31:49 +01:00
//
// Only handle base 2 -> 36
//
2018-12-25 19:09:58 +01:00
if (base < 2 || base > 36)
return NULL;
2019-01-01 17:37:58 +01:00
#if defined(_NEED_ITOA) || defined(_NEED_LTOA)
2019-01-14 14:31:49 +01:00
//
// Deal with negatives
//
2018-12-25 19:09:58 +01:00
if (i < 0) {
neg = 1;
i = -i;
}
2019-01-01 17:37:58 +01:00
#endif
2019-01-14 14:31:49 +01:00
//
// Deal with zero separately
//
2018-12-25 19:09:58 +01:00
if (i == 0) {
*str++ = '0';
}
2019-01-14 14:31:49 +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';
2019-01-14 14:31:49 +01:00
//
// Reverse the string
//
return strrev2(orig);
2018-12-25 19:09:58 +01:00
}