Skip to content

Instantly share code, notes, and snippets.

@robinkunde
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinkunde/dc3f18f8c2cb250d7a38 to your computer and use it in GitHub Desktop.
Save robinkunde/dc3f18f8c2cb250d7a38 to your computer and use it in GitHub Desktop.
High performance function for creating hex encoded string from NSData
NSString *hexEncodedStringFromData(NSData *data)
{
static const char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
// Store the length, otherwise it would be re-evalued on each loop iteration
NSUInteger length = data.length;
// malloc result data NULL terminated string
char *resultData = malloc(length * 2 + 1);
const unsigned char *sourceData = (const unsigned char *)data.bytes;
// at least in my tests, performing the multiplication twice like this is always faster than
// storing & reusing it or using a separate counter that you increment by 2
for (NSUInteger index = 0; index < length; index++) {
// shift off 4 lowers bits
resultData[index * 2] = hexChars[sourceData[index] >> 4];
// mask off upper 4 bits
resultData[index * 2 + 1] = hexChars[sourceData[index] & 15];
}
// NULL termination
resultData[length * 2] = 0;
// convert result to NSString
NSString *result = [NSString stringWithCString:resultData encoding:NSASCIIStringEncoding];
free(resultData);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment