将十六进制字符串转换为十六进制数据

时间:2021-06-06 15:45:42

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.

我目前有一个包含十六进制值的NSString。我需要将这个NSString对象转换为NSData对象,而不需要改变它的内容。

1 个解决方案

#1


8  

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对象的调试输出(如果您只是NSData对象,那么您在控制台中会得到什么)返回到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].

这不是我最健壮的代码,但是它可以解析[nsdata_object description]。

#1


8  

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对象的调试输出(如果您只是NSData对象,那么您在控制台中会得到什么)返回到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].

这不是我最健壮的代码,但是它可以解析[nsdata_object description]。