如何将HEX转换为Objective-C中的NSString?

我有一个hexstring像“68656C6C6F”这意味着“你好”的NSString。

现在我想把hexstring转换成另一个显示“hello”的NSString对象。 怎么做 ?

我相信有更好,更聪明的方法来做到这一点,但这个解决scheme确实有效。

NSString * str = @"68656C6C6F"; NSMutableString * newString = [[[NSMutableString alloc] init] autorelease]; 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; } 

这应该做到这一点:

 - (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; } 

我认为build议initWithFormat的人是最好的答案,因为它是客观的C,而不是ObjC,C的混合(尽pipe示例代码有点简洁)..我做了以下

 unsigned int resInit = 0x1013; if (0 != resInit) { NSString *s = [[NSString alloc] initWithFormat:@"Error code 0x%lX", resInit]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Initialised failed" message:s delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; [s release]; } 
 +(NSString*)intToHexString:(NSInteger)value { return [[NSString alloc] initWithFormat:@"%lX", value]; }