{ ademcan's snippets }
Convert a NSString hexstring to a NSData [objectivec]
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]
Convert a NSData hexstring to a NSString [objectivec]
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]