John Smith
John Smith

Reputation: 33

Converting hex string to hex data

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.

Upvotes: 3

Views: 1854

Answers (1)

Orangenhain
Orangenhain

Reputation: 4110

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].

Upvotes: 8

Related Questions