Last active
August 29, 2015 14:01
-
-
Save oelna/a01eef5fa8554e0a058b to your computer and use it in GitHub Desktop.
Two functions to convert a base 10 NSNumber to a base 36 NSString and the other way around, using C
This file contains 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
/* 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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
NSLog(@"output base 10 to 36: %@", [ClassName toBase10:@42891 withBase:36]);
NSLog(@"output base 36 to 10: %@", [ClassName fromBase10:@"x3f" withBase:36]);