0

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;

}
Edward Tattsyrup
  • 245
  • 1
  • 3
  • 15

1 Answers1

1

So it seems this returns the format I need.

NSString * inputStr = @"11111bfb";


    NSMutableArray *charByteArray = [[NSMutableArray alloc]initWithCapacity:1];
    int i = 0;
    for (i = 0; i+2 <= inputStr.length; i+=2) {

        NSRange range = NSMakeRange(i, 2);
        NSString* charStr = [inputStr substringWithRange:range];
        [charByteArray addObject:[NSString stringWithFormat:@"0x%@",charStr]];

    }
Edward Tattsyrup
  • 245
  • 1
  • 3
  • 15