Created
January 20, 2013 04:28
-
-
Save 314maro/4576684 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #import <Foundation/Foundation.h> | |
| int intFromChar(char aChar, int notation) { | |
| // error | |
| if (!isalnum(aChar)) | |
| return INT_MAX; | |
| int result = 0; | |
| if (isdigit(aChar)) // '0'-'9' | |
| result = aChar - 48; | |
| else // 'a'-'z', 'A'-'Z' | |
| result = tolower(aChar) - 97 + 10; | |
| if (result >= notation) | |
| return INT_MAX; | |
| else | |
| return result; | |
| } | |
| int intFromString(NSString* aString, int notation) { | |
| // error | |
| if (notation > 10 + 26) | |
| return INT_MAX; | |
| int result = 0, flag = 1; | |
| int i = 0; | |
| if ([aString characterAtIndex:0] == '-') { | |
| flag = -1; | |
| i = 1; | |
| } | |
| for (; i < aString.length; i++) { | |
| int num = intFromChar([aString characterAtIndex:i], notation); | |
| if (num < notation) | |
| result += num * flag * pow(notation, aString.length - i - 1); | |
| else { | |
| result = INT_MAX; | |
| break; | |
| } | |
| } | |
| return result; | |
| } | |
| char charFromInt(int aNumber, int notation) { | |
| // error | |
| if (aNumber >= notation) | |
| return '\0'; | |
| if (aNumber < 10) | |
| return aNumber + 48; | |
| else | |
| return aNumber + 97 - 10; | |
| } | |
| NSString* stringFromInt(int aNumber, int notation) { | |
| // error | |
| if (aNumber == INT_MAX) | |
| return @"error"; | |
| NSString *numString = @""; | |
| int x = aNumber; | |
| if (x == 0) | |
| return @"0"; | |
| else if (x < 0) { | |
| x = -x; | |
| numString = [numString stringByAppendingString:@"-"]; | |
| } | |
| for (int i = floor(log(x)/log(notation)); i >= 0; i--) { | |
| int digit = pow(notation, i); | |
| char numChar = charFromInt(x / digit, notation); | |
| if (x / digit < notation) | |
| numString = [numString stringByAppendingFormat:@"%c", numChar]; | |
| x = x % digit; | |
| } | |
| return numString; | |
| } | |
| NSString* convert(NSString* fromString, int fromNotation, int toNotation) { | |
| if (fromNotation < 1 || toNotation < 1 || fromNotation > 10 + 26 || toNotation > 10 + 26) | |
| return nil; | |
| int num = intFromString(fromString, fromNotation); | |
| return stringFromInt(num, toNotation); | |
| } | |
| int main(int argc, char **argv) { | |
| @autoreleasepool { | |
| NSLog(@"%@", convert(@"10", 10, 16)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment