常在一些网站源码中看到&#x开头的内容,这是转化成unicode编码后的汉字。
--------------------------------------------unicode编码后的汉字(呵呵)转化成中文(呵呵)---------------------------------------
step1:unicode解码(呵呵 ---------------- \u5475\u5475)
+(NSString *)change:(NSString *)str { NSString *changeStr = @""; if (!str||[str isEqualToString:@""]) { return @""; } changeStr = [str stringByReplacingOccurrencesOfString:@"&#x" withString:@"\\u"]; changeStr = [changeStr stringByReplacingOccurrencesOfString:@";" withString:@""]; return changeStr; }
step2:unicode转UTF-8(\u5475\u5475 ---------------- 呵呵)
+(NSString *) unicodeToUtf8:(NSString *)string { NSString *tempStr1 = [string stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"]; NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]; NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""]; NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding]; NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:NULL]; return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"]; }
------------------------------------------------------------UrlEncode--------------------------------------------------
对UTF-8中文UrlEncode编码(呵呵------------------------%e5%91%b5%e5%91%b5)
- (NSString *)URLEncodedString { NSString *encodedString = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&‘()*+,-./:;[email protected]_~%#[]", NULL, kCFStringEncodingUTF8); return encodedString; } - (NSString*)URLDecodedString { NSString *result = ( NSString *) CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)self, CFSTR(""), kCFStringEncodingUTF8)); return result; }
对gb2312中文UrlEncode编码(呵呵-----------------------%ba%c7%ba%c7)
MD5加密
#import "CommonCrypto/CommonDigest.h" @implementation MD5 +(NSString *) md5: (NSString *) inPutText { const char *cStr = [inPutText UTF8String]; unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5(cStr, strlen(cStr), result); return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7], result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15] ] lowercaseString]; } +(NSString *) MD5: (NSString *) inPutText { const char *cStr = [inPutText UTF8String]; unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5(cStr, strlen(cStr), result); return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7], result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15] ] uppercaseString]; }
.
编码和解码及MD5加密
时间: 2024-10-30 17:40:38