Last active
August 29, 2015 14:02
-
-
Save guilhermearaujo/f501852bf765ec31ad65 to your computer and use it in GitHub Desktop.
NSString+BaseConvertion
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
// | |
// NSString+BaseConvertion.h | |
// | |
// Created by Guilherme Araújo on 31/05/14. | |
// Copyright (c) 2014 Guilherme Araújo. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
@interface NSString (BaseConvertion) | |
+ (NSString *)stringWithInteger:(NSUInteger)number onBase:(NSUInteger)base padding:(NSUInteger)padding; | |
- (NSUInteger)integerFromBase:(NSUInteger)base; | |
@end |
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
// | |
// NSString+BaseConvertion.m | |
// | |
// Created by Guilherme Araújo on 31/05/14. | |
// Copyright (c) 2014 Guilherme Araújo. All rights reserved. | |
// | |
#import "NSString+BaseConvertion.h" | |
@implementation NSString (BaseConvertion) | |
+ (NSString *)stringWithInteger:(NSUInteger)number onBase:(NSUInteger)base padding:(NSUInteger)padding { | |
if (base < 2 || base > 62) { | |
NSLog(@"NSString+BaseConvertion: invalid base. Base must be a value between 2 and 62"); | |
return nil; | |
} | |
NSString *alphabet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; | |
NSMutableString *encoded = [[NSMutableString alloc] init]; | |
do { | |
[encoded insertString:[alphabet substringWithRange:NSMakeRange(number % base, 1)] atIndex:0]; | |
} while (number /= base); | |
while ([encoded length] < padding) { | |
[encoded insertString:@"0" atIndex:0]; | |
} | |
return encoded; | |
} | |
- (NSUInteger)integerFromBase:(NSUInteger)base { | |
if (base < 2 || base > 62) { | |
NSLog(@"NSString+BaseConvertion: invalid base. Base must be a value between 2 and 62"); | |
return -1; | |
} | |
NSString *alphabet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; | |
NSUInteger number = 0; | |
for (NSUInteger power = [self length]; power > 0; power--) { | |
NSUInteger value = [alphabet rangeOfString:[self substringWithRange:NSMakeRange(power - 1, 1)]].location; | |
number += value * (NSUInteger)pow(base, [self length] - power); | |
} | |
return number; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment