diff --git a/CoreBitcoin/BTCData.m b/CoreBitcoin/BTCData.m index 85e2bd67..a7fb6b4d 100644 --- a/CoreBitcoin/BTCData.m +++ b/CoreBitcoin/BTCData.m @@ -183,20 +183,36 @@ static inline int BTCFairCoinFlip() { return [[NSData alloc] initWithBytesNoCopy:buf length:len/2]; } - -NSString* BTCHexFromDataWithFormat(NSData* data, const char* format) { - if (!data) return nil; - - NSUInteger length = data.length; - if (length == 0) return @""; - - NSMutableData* resultdata = [NSMutableData dataWithLength:length * 2]; - char *dest = resultdata.mutableBytes; - unsigned const char *src = data.bytes; - for (int i = 0; i < length; ++i) { - sprintf(dest + i*2, format, (unsigned int)(src[i])); +static const char hexValues[16] = { + '0', '1', '2', '3', + '4', '5', '6', '7', + '8', '9', 'a', 'b', + 'c', 'd', 'e', 'f', +}; + +static const char upperHexValues[16] = { + '0', '1', '2', '3', + '4', '5', '6', '7', + '8', '9', 'A', 'B', + 'C', 'D', 'E', 'F', +}; + +static NSString* BTCHexFromDataWithCharset(NSData* data, const char* charset) { + size_t inLength = data.length; + size_t length = inLength * 2; + uint8_t *outString = malloc(length); + const unsigned char *bytes = data.bytes; + for (uint32_t i = 0; i < inLength; i++) { + unsigned char byte = bytes[i]; + outString[i*2] = charset[byte >> 4]; + outString[i*2+1] = charset[byte & 0x0F]; } - return [[NSString alloc] initWithData:resultdata encoding:NSASCIIStringEncoding]; + return [[NSString alloc] + initWithBytesNoCopy:outString + length:length + encoding:NSASCIIStringEncoding + freeWhenDone:YES + ]; } NSString* BTCHexStringFromData(NSData* data) { // deprecated @@ -208,11 +224,11 @@ static inline int BTCFairCoinFlip() { } NSString* BTCHexFromData(NSData* data) { - return BTCHexFromDataWithFormat(data, "%02x"); + return BTCHexFromDataWithCharset(data, hexValues); } NSString* BTCUppercaseHexFromData(NSData* data) { - return BTCHexFromDataWithFormat(data, "%02X"); + return BTCHexFromDataWithCharset(data, upperHexValues); }