I have a string and I'm trying to break it up and add it to an NSArray. I've recently moved from Java (android) to iOS... I wrote a java function which converted a hexString/string to a byte array. I can't see an obvious way to do it with objective-c. Not sure what I've attempted is even close to achieving what I need.
Heres my string
NSString *code = @"11111bfb";
This is the output I hope to achieve
NSArray *codeArray = @[@0x11, @0x11, @0x1b, @0xfb];
Method
- (NSData *)dataFromHexString:(NSString *) string {
if([string length] % 2 == 1){
string = [@"0x"stringByAppendingString:string];
}
const char *chars = [string UTF8String];
int i = 0, len = (int)[string length];
NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
char byteChars[4] = {'\0','\0','\0','\0'};
unsigned long wholeByte;
while (i < len) {
byteChars[0] = chars[i++];
byteChars[1] = chars[i++];
wholeByte = strtoul(byteChars, NULL, 16);
[data appendBytes:&wholeByte length:1];
}
return data;
}