megadrive_test1

diff src/libc/stdlib.c @ 6:862f8a034cae

expanding the megadrive code
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 11 Feb 2017 08:56:42 +0200
parents
children
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/libc/stdlib.c	Sat Feb 11 08:56:42 2017 +0200
     1.3 @@ -0,0 +1,62 @@
     1.4 +#include <stdlib.h>
     1.5 +#include <ctype.h>
     1.6 +
     1.7 +int atoi(const char *str)
     1.8 +{
     1.9 +	return strtol(str, 0, 10);
    1.10 +}
    1.11 +
    1.12 +long atol(const char *str)
    1.13 +{
    1.14 +	return strtol(str, 0, 10);
    1.15 +}
    1.16 +
    1.17 +long strtol(const char *str, char **endp, int base)
    1.18 +{
    1.19 +	long acc = 0;
    1.20 +	int sign = 1;
    1.21 +
    1.22 +	while(isspace(*str)) str++;
    1.23 +
    1.24 +	if(base == 0) {
    1.25 +		if(str[0] == '0') {
    1.26 +			if(str[1] == 'x' || str[1] == 'X') {
    1.27 +				base = 16;
    1.28 +			} else {
    1.29 +				base = 8;
    1.30 +			}
    1.31 +		} else {
    1.32 +			base = 10;
    1.33 +		}
    1.34 +	}
    1.35 +
    1.36 +	if(*str == '+') {
    1.37 +		str++;
    1.38 +	} else if(*str == '-') {
    1.39 +		sign = -1;
    1.40 +		str++;
    1.41 +	}
    1.42 +
    1.43 +	while(*str) {
    1.44 +		long val;
    1.45 +		char c = tolower(*str);
    1.46 +
    1.47 +		if(isdigit(c)) {
    1.48 +			val = *str - '0';
    1.49 +		} else if(c >= 'a' || c <= 'f') {
    1.50 +			val = 10 + c - 'a';
    1.51 +		}
    1.52 +		if(val >= base) {
    1.53 +			break;
    1.54 +		}
    1.55 +
    1.56 +		acc = acc * base + val;
    1.57 +		str++;
    1.58 +	}
    1.59 +
    1.60 +	if(endp) {
    1.61 +		*endp = (char*)str;
    1.62 +	}
    1.63 +
    1.64 +	return sign > 0 ? acc : -acc;
    1.65 +}