Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <ctype.h>
- #include <errno.h>
- #include <limits.h>
- long strtol(const char *s, char *endptr, int base)
- {
- int power;
- int sign = 1;
- const char *ptr = s;
- long result = 0;
- /*check the base*/
- if ((base<2 || base >36) && base!=0)
- {
- errno=EINVAL;
- return 0;
- }
- if(*ptr == '\n')
- return 0;
- /*delating spaces and tabulations at the begining*/
- while(isspace(ptr))
- ptr++;
- if(!ptr) return 0;
- /*case: base =0, string starts with '0x' or '0X' (16) or '0' (8) or it's (10)*/
- if(base == 0)
- {
- if(*ptr == '0' && (*ptr+1 == 'x' || *ptr+1 == 'X'))
- base = 16;
- else
- if(*ptr == '0')
- base = 8;
- else
- base=10;
- }
- if(*ptr=='+')
- ptr = ptr+1;
- else
- if(*ptr == '-')
- {
- sign = -1;
- ptr = ptr+1;
- }
- /*case: base = 16, string starts with '0x' or '0X'*/
- if(base == 16 && (*ptr == '0' && (*(ptr+1)== 'x' || *(ptr+1)== 'X')))
- ptr = ptr+2;
- /*case: base = 8, string starts with 0*/
- if(base == 8 && *ptr == '0')
- ptr = ptr+1;
- /*remove zeros at the begining*/
- while(*ptr == '0') ptr++;
- if(!ptr)
- {
- return 0;
- }
- /*set end pointer*/
- for(*endptr = ptr; endptr < (ptr +strlen(ptr)-1); endptr++)
- if(converter(*endptr)>(base-1) || converter(*endptr)==-1)
- break;
- power = 1;
- for(endptr-=1; endptr>=ptr; endptr--)
- {
- result += converter(*endptr) * power;
- power *=base;
- }
- if(result*sign> LONG_MAX)
- {
- errno = ERANGE;
- return LONG_MAX;
- }
- if(result*sign<LONG_MIN)
- {
- errno = ERANGE;
- return LONG_MIN;
- }
- return result*sign;
- }
- /** function converting letters and numbers (char type) to numbers(int type)
- * @param sth the character
- */
- int converter(char sth)
- {
- if(sth>='0' && sth<='9') return sth - '0';
- if(sth>='a' && sth<='z') return sth - 'a' + 10;
- if(sth>='A' && sth>='Z') return sth-'A' + 10;
- return -1;
- }
Add Comment
Please, Sign In to add comment