Snippet's details

Convert a NSString hexstring to a NSData [objectivec]

05.09.2018     ademcan      ios objc hexstring 

  How to convert a NSString hexstring ("a4a67b439c94efd9...") into a NSData hexstring (<a4a67b43 9c94efd9...>)
NSString *hexStr = YOUR_NSSTRING_HEXSTRING;
// remove whitespace from the hexstring
hexStr = [hexStr stringByReplacingOccurrencesOfString:@" " withString:@""];
// instantiate an empty NSMutableData (it will represent the final NSData)
NSMutableData *hexData= [[NSMutableData alloc] init];
unsigned char whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
// converting hex to bytes
for (int i=0; i < [hexStr length]/2; i++) {
	byte_chars[0] = [hexStr characterAtIndex:i*2];
	byte_chars[1] = [hexStr characterAtIndex:i*2+1];
	whole_byte = strtol(byte_chars, NULL, 16);
	[hexData appendBytes:&whole_byte length:1];
}
0/5 - [0 rating]