Last active
December 18, 2015 21:48
-
-
Save claybridges/5849621 to your computer and use it in GitHub Desktop.
HexNSStringFromBytes
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 *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