diff options
Diffstat (limited to 'src/stdlib.c')
-rw-r--r-- | src/stdlib.c | 43 |
1 files changed, 42 insertions, 1 deletions
diff --git a/src/stdlib.c b/src/stdlib.c index 9a9425f..46bdce8 100644 --- a/src/stdlib.c +++ b/src/stdlib.c @@ -1,7 +1,48 @@ +#include <stdbool.h> +#include "string.h" #include "stdlib.h" +#include "stddef.h" +static void strreverse( char *s ) +{ + char *end = s + strlen( s ) - 1; + + while( s < end ) { + // XOR swap; + *s ^= *end; + *end ^= *s; + *s ^= *end; + s++; + end--; + } +} + char *itoa( int v, char *s, int base ) { - //~ *s = '\0'; + static char digit[] = "0123456789ABCDEF"; + bool sign = false; + char *p = s; + + if( base < 2 || base > 16 ) { + return NULL; + } + + if( v < 0 ) { + v = -v; + sign = true; + } + + do { + *p++ = digit[v % base]; + } while( ( v /= base ) > 0 ); + + if( sign ) { + *p++ = '-'; + } + *p = '\0'; + + strreverse( s ); + return s; } + |