Snippet's details

Convert a NSData hexstring to a NSString [objectivec]

10.08.2018     ademcan      ios objc 

  How to convert a NSData hexstring (<a4a67b43 9c94efd9...>) bytes into NSString hexstring ("a4a67b439c94efd9...")
NSData *data = YOUR_NSDATA_HEXSTRING;
// 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:@"%02lx", (NSUInteger)buf[t]];
}
NSLog(@"Hexstring: %@", mutableString);
// save as NSString
NSString * hexstring =mutableString;
0/5 - [0 rating]