关于十六进制 hex 转换成NSString 中文乱码问题
今天在cocoaChina上看到有人问到,以前记得在哪儿看到过解决方法,特此标记一下:
- (NSString *)stringFromHexString:(NSString *)hexString { // eg. hexString = @"8c376b4c" char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1); bzero(myBuffer, [hexString length] / 2 + 1); for (int i = 0; i < [hexString length] - 1; i += 2) { unsigned int anInt; NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)]; NSScanner * scanner = [[[NSScanner alloc] initWithString:hexCharStr] autorelease]; [scanner scanHexInt:&anInt]; myBuffer[i / 2] = (char)anInt; } NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:NSUnicodeStringEncoding]; // printf("%s\n", myBuffer); free(myBuffer); NSString *temp1 = [unicodeString stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"]; NSString *temp2 = [temp1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]; NSString *temp3 = [[@"\"" stringByAppendingString:temp2] stringByAppendingString:@"\""]; NSData *tempData = [temp3 dataUsingEncoding:NSUTF8StringEncoding]; NSString *temp4 = [NSPropertyListSerialization propertyListFromData:tempData mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:NULL]; NSString *string = [temp4 stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"]; NSLog(@"-------string----%@", string); //输出 谷歌 return string; }