1. 程式人生 > >ios unicode轉漢字/漢字轉gbk

ios unicode轉漢字/漢字轉gbk

//身份證姓名讀取高低位需要轉換,unicode轉漢字,每2位元組代表一個漢字

NSString *name = [string substringToIndex:60];

NSString *nameStr = @"";

for (NSInteger i=0 ;i<name.length;)

{

NSString *tempstr = [name substringWithRange:NSMakeRange(i,4)];//每兩位元組一個漢字

if([tempstr isEqualToString:@"2000"])

{

break;

}

NSString *tempNameStr1 = [tempstr substringWithRange

:NSMakeRange(2,2)];//高低位轉換

NSString *tempNameStr2 = [tempstr substringWithRange:NSMakeRange(0,2)];

NSString *tempName = [@"u" stringByAppendingString:tempNameStr1];//拼接\u

tempName = [@"\\" stringByAppendingString:tempName];

tempName = [tempName stringByAppendingString:tempNameStr2];

nameStr = [nameStr stringByAppendingString

:tempName];

i+=4;

}

nameStr =[weakSelf replaceUnicode:nameStr];

- (NSString*) replaceUnicode:(NSString*)TransformUnicodeString

{

NSString*tepStr1 = [TransformUnicodeString stringByReplacingOccurrencesOfString:@"\\u"withString:@"\\U"];

NSString*tepStr2 = [tepStr1 stringByReplacingOccurrencesOfString:@"\""withString:

@"\\\""];

NSString*tepStr3 = [[@"\""stringByAppendingString:tepStr2]stringByAppendingString:@"\""];

NSData*tepData = [tepStr3 dataUsingEncoding:NSUTF8StringEncoding];

NSString*axiba = [NSPropertyListSerializationpropertyListWithData:tepData options:NSPropertyListMutableContainersformat:NULLerror:NULL];

return [axiba stringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];

}

漢字轉gbk

NSStringEncodin gbkEncoding=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);

NSData*aData = [“要轉的漢字” dataUsingEncoding: gbkEncoding];

NSString *result = [NSStringTool convertDataToHexStr:aData];