Skip to content

Instantly share code, notes, and snippets.

@oelna
Last active Aug 29, 2015
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, using C
/* Arno Richter, May 2014 */
- (NSString *)toBase10:(NSNumber *)fromValue withBase:(int)base {
char base_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
unsigned long int number_to_convert = [fromValue unsignedLongValue];
int converted_number[64];
int index = 0;
char return_string[64] = "";
while(number_to_convert != 0) {
converted_number[index] = number_to_convert % base;
number_to_convert = number_to_convert / base;
++index;
}
--index;
for( ; index>=0; index--) {
int len = strlen(return_string);
return_string[len] = base_digits[converted_number[index]];
return_string[len+1] = '\0';
}
return [NSString stringWithFormat:@"%s", return_string];
}
- (NSNumber *)fromBase10:(NSString *)fromValue withBase:(int)base {
const char *rawinput = [fromValue UTF8String];
size_t len = strlen(rawinput) + 1;
char mac [len];
memcpy(mac, rawinput, len);
long output = strtol(mac,NULL,base);
return [NSNumber numberWithLong:output];
}
@oelna

This comment has been minimized.

Copy link
Owner Author

@oelna oelna commented May 11, 2014

Usage:
NSLog(@"output base 10 to 36: %@", [ClassName toBase10:@42891 withBase:36]);
NSLog(@"output base 36 to 10: %@", [ClassName fromBase10:@"x3f" withBase:36]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment