How to convert HEX to NSString in Objective-C?

后端 未结 5 1578
终归单人心
终归单人心 2020-11-27 22:06

I have a NSString with hex string like \"68656C6C6F\" which means \"hello\".

Now I want to convert the hex string into another NSString object which shows \"hello\"

5条回答
  •  渐次进展
    2020-11-27 22:33

    This should do it:

    - (NSString *)stringFromHexString:(NSString *)hexString {
    
        // The hex codes should all be two characters.
        if (([hexString length] % 2) != 0)
            return nil;
    
        NSMutableString *string = [NSMutableString string];
    
        for (NSInteger i = 0; i < [hexString length]; i += 2) {
    
            NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];
            NSInteger decimalValue = 0;
            sscanf([hex UTF8String], "%x", &decimalValue);
            [string appendFormat:@"%c", decimalValue];
        }
    
        return string;
    }
    

提交回复
热议问题