August 3, 2018 ademcan No comments

How to convert a NSData hexstring to a NSString in Objective-C

At the QRL we are dealing a lot with hexstrings. Several of our API functions return results in hexstring format and it is sometimes important to be able to reuse them for another call. Here is how to convert a hexstring you received as NSData object (and looks like <24501f40 6cf57975 676b6d34 95d4cd7d 14541ddd 4d44fa4a f08e6faf 9d15252b>) to a string (in our case “24501f406cf57975676b6d3495d4cd7d14541ddd4d44fa4af08e6faf9d15252b”):

// we first need to get the length of our hexstring
// data.lenght returns the lenght in bytes, so we *2 to get as hexstring
NSUInteger capacity = data.length * 2;
// Create a new NSMutableString with the correct lenght
NSMutableString *mutableString = [NSMutableString stringWithCapacity:capacity];
// get the bytes of data to be able to loop through it
const unsigned char *buf = (const unsigned char*) [data bytes];

NSInteger t;
for (t=0; t<data.length; ++t) {
  NSLog(@"GLYPH at t : %c", buf[t]);
  NSLog(@"DECIMAL at t  : %lu", (NSUInteger)buf[t]);
  // "%02X" will append a 0 if the value is less than 2 digits (i.e. 4 becomes 04)
  [mutableString appendFormat:@"%02X", (NSUInteger)buf[t]];
NSLog(@"Hexstring: %@", mutableString);
// save as NSString
NSString * hexstring =mutableString;

You can check the decimal, hex and corresponding glyph here.

SO question
String Format Specifiers [Apple dev]
Bits and Bytes

Leave a Reply

Your email address will not be published. Required fields are marked *