/******************************************** * My AtoI * lovepump * lovepump@gatheringofgray.com * * Convert ascii (base anything up to 35) to base 10 integer * * This Version - Positive numbers only * ********************************************/ #define ATOI_ERROR_BASE -1 #define ATOI_ERROR_NODIGIT -2 #define ATOI_INVALID_DIGIT -3 /* Usage: str* - pointer to a NULL terminated string, base 'base' ascii "number" base - number system basis for conversion up to 36 (Z) */ int pow(int num, int exp) { int i, result = 1; if(exp == 0) return 1; for(i = 0; i < exp; i++) result *= num; return result; } int my_atoi(const char *str, unsigned int base) { if(base > 36) return ATOI_ERROR_BASE; if(str == 0) return ATOI_ERROR_NODIGIT; unsigned int result = 0; const char *cursor, *low; cursor = str; for(;*cursor != '\0'; cursor++); cursor--; low = cursor; while(cursor >= str) { if(*cursor >= 48 && (base > 10?*cursor <=57:*cursor <= (48 + base))) result += (*cursor - 48) * pow(base,(low - cursor)); else if(base > 10 && (*cursor >= 65 && *cursor < (65 + base - 10))) result += (*cursor - 65 + 10) * pow(base,(low - cursor)); else return ATOI_INVALID_DIGIT; cursor--; } return result; } void my_itoa(unsigned int num, unsigned int base, char *str) { const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; unsigned int magnitude = 0, remainder; int length = 0, cursor = 0; if(base < 2 || base > 36) { *str = '\0'; return; } while(pow(base, length) < num)length++; remainder = num; str[length] = '\0'; cursor = length - 1; while(length >= 0) { while(pow(base, length) * magnitude <= remainder) magnitude++; magnitude--; str[cursor - length] = digits[magnitude]; remainder -= pow(base,length)*magnitude; length--; magnitude = 0; } }