Converting hex string to hex data

2019-02-19 00:39发布

问题:

I currently have an NSString containing hex values. I need to convert this NSString object into an NSData object, without changing its contents at all.

回答1:

I use this code to "parse" the debug output of an NSData object (what you get in the console if you just NSLog an NSData object) back into NSData:

-(NSData*) bytesFromHexString:(NSString *)aString;
{
    NSString *theString = [[aString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString:nil];

    NSMutableData* data = [NSMutableData data];
    int idx;
    for (idx = 0; idx+2 <= theString.length; idx+=2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString* hexStr = [theString substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        unsigned int intValue;
        if ([scanner scanHexInt:&intValue])
            [data appendBytes:&intValue length:1];
    }
    return data;
}

It's not my most robust code, but it does the job of parsing [nsdata_object description].