Skip to content

Instantly share code, notes, and snippets.

@claybridges
Last active December 18, 2015 21:48
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 claybridges/5849621 to your computer and use it in GitHub Desktop.
Save claybridges/5849621 to your computer and use it in GitHub Desktop.
HexNSStringFromBytes
NSString *HexNSStringFromBytes(uint8_t *bytes, NSUInteger count) {
char *hexCString = calloc(count * 2 + 1, sizeof(char *));
static char hexLookup[] = "0123456789abcdef";
NSMutableString* testString = [NSMutableString string];
for (int i = 0; i < count; ++i) {
uint8_t fullByte = bytes[i];
// each byte converts to two hex characters
hexCString[2 * i] = hexLookup[fullByte >> 4]; // high-order nibble first
hexCString[2 * i + 1] = hexLookup[fullByte & 0x0F]; // low-order
[testString appendFormat:@"%02x", bytes[i]];
}
NSString *hexString = [NSString stringWithUTF8String:hexCString];
free(hexCString);
assert([hexString isEqualToString:testString]);
return hexString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment