Skip to content

Instantly share code, notes, and snippets.

@hlung
Last active March 19, 2020 08:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save hlung/6333269 to your computer and use it in GitHub Desktop.
Save hlung/6333269 to your computer and use it in GitHub Desktop.
Converts NSData to a hexadecimal string.
/** Converts NSData to a hexadecimal string. */
@interface NSData (NSData_hexadecimalString)
/** Changes NSData object to a hex string.
@returns hexadecimal string of NSData. Empty string if data is empty.*/
- (NSString *)hexadecimalString;
@end
@implementation NSData (NSData_hexadecimalString)
- (NSString *)hexadecimalString {
const unsigned char *dataBuffer = (const unsigned char *)[self bytes];
if (!dataBuffer) return [NSString string];
NSUInteger dataLength = [self length];
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i)
[hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];
return [NSString stringWithString:hexString];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment