Skip to content

Instantly share code, notes, and snippets.

@oelna
Created May 11, 2014
Embed
What would you like to do?
Two functions to convert a base 10 NSNumber to a base 36 NSString and the other way around
/* Arno Richter, May 2014 */
- (NSNumber *)getIndexOf:(NSString *)c alphabet:(NSString*)string {
for(int i=0; i<[string length]; i++) {
if([c characterAtIndex:0] == [string characterAtIndex:i]) {
return [NSNumber numberWithInteger:i];
}
}
return [NSNumber numberWithInt:-1];
}
- (NSNumber *)base36To10:(NSString *)fromValue {
NSString *alphabet = @"0123456789abcdefghijklmnopqrstuvwxyz";
NSInteger total = 0;
NSInteger power = 1;
NSInteger sum = 0;
for(int i=0; i<[fromValue length]; i++) {
NSString *character = [fromValue substringWithRange:NSMakeRange(i, 1)];
NSNumber *decimal = [self getIndexOf:character alphabet:alphabet];
if(i == ([fromValue length]-1)) {
power = 1;
} else {
power = pow(36, [fromValue length]-i-1);
}
sum = [decimal intValue] * power;
total = total + sum;
}
return [NSNumber numberWithInteger:total];
}
- (NSString *)base10To36:(NSNumber *)fromValue {
NSString *alphabet = @"0123456789abcdefghijklmnopqrstuvwxyz";
NSMutableArray *returnArray = [[NSMutableArray alloc] init];
NSMutableString *returnString = [[NSMutableString alloc] init];
NSInteger manual = [fromValue intValue];
while(manual > 0) {
NSInteger rest = manual % 36;
[returnArray addObject:[NSNumber numberWithInteger:rest]];
manual = manual / 36;
}
NSArray *reversed = [[returnArray reverseObjectEnumerator] allObjects];
for(int i=0; i<[reversed count]; i++) {
NSString *character = [alphabet substringWithRange:NSMakeRange([[reversed objectAtIndex:i] intValue], 1)];
[returnString appendString:character];
}
return returnString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment