Created
March 13, 2013 21:30
-
-
Save mayoff/5156496 to your computer and use it in GitHub Desktop.
Test program that converts an arbitrary-precision decimal digit string to a hex digit string.
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
#import <Foundation/Foundation.h> | |
#import <vector> | |
// index 0 is the least significant digit | |
typedef std::vector<uint16_t> BigInt; | |
static void insertDecimalDigit(BigInt &b, uint16_t decimalDigit) { | |
uint32_t carry = decimalDigit; | |
for (size_t i = 0; i < b.size(); ++i) { | |
uint32_t product = b[i] * (uint32_t)10 + carry; | |
b[i] = (uint16_t)product; | |
carry = product >> 16; | |
} | |
if (carry > 0) { | |
b.push_back(carry); | |
} | |
} | |
@interface NSString (BigDecimalToHex) | |
- (NSString *)hexStringFromDecimalString; | |
@end | |
@implementation NSString (BigDecimalToHex) | |
- (NSString *)hexStringFromDecimalString { | |
NSUInteger length = self.length; | |
unichar decimalCharacters[length]; | |
[self getCharacters:decimalCharacters range:NSMakeRange(0, length)]; | |
BigInt b; | |
for (NSUInteger i = 0; i < length; ++i) { | |
insertDecimalDigit(b, decimalCharacters[i] - '0'); | |
} | |
if (b.size() == 0) { | |
return @"0"; | |
} | |
NSMutableString *hexString = [NSMutableString stringWithFormat:@"%X", b.back()]; | |
for (ssize_t i = b.size() - 2; i >= 0; --i) { | |
[hexString appendFormat:@"%04X", b[i]]; | |
} | |
return hexString; | |
} | |
@end | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
NSString *exampleInput = @"423723487924398723478243789243879243978234"; | |
NSString *exampleOutput = @"4DD361F5A772159224CE9EB0C215D2915FA"; | |
NSString *myOutput = [exampleInput hexStringFromDecimalString]; | |
NSLog(@"%@", exampleInput); | |
NSLog(@"%@", exampleOutput); | |
NSLog(@"%@", myOutput); | |
NSLog(@"isEqualToString -> %d", (int)[myOutput isEqualToString:exampleOutput]); | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment