我有一个包含十六进制值的NSString,我想以ASCII转换。我怎么能这样做?
Any?
我试过的不正确的方法:
我在similar question上尝试了以下方法,但它对我不起作用:
NSString * hexString = // some value
NSString * asciiString = // ? convert hexString to ASCI somehow
答案 0 :(得分:2)
这对我有用:
NSString * str = @"312d4555";
NSMutableString * newString = [[NSMutableString alloc] init];
int i = 0;
while (i < [str length]){
NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)];
int value = 0;
sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
[newString appendFormat:@"%c", (char)value];
i+=2;
}
NSLog(@"%@", newString);
输出为:hello