ios 端如何 进行同样的unicode 解码 转码, 不太懂Java,希望大神贴上ios unicode代码转码解码
public static String string2Unicode(String string) {
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
unicode.append("\\u" + Integer.toHexString(c));
}
String str = unicode.toString();
return str.replaceAll("\\\\","0x");
}
public static String unicode2String(String unicode) {
String str = unicode.replace("0x", "\\");
StringBuffer string = new StringBuffer();
String[] hex = str.split("\\\\u");
for (int i = 1; i < hex.length; i++) {
int data = Integer.parseInt(hex[i], 16);
string.append((char) data);
}
return string.toString();
}
回答:
如果你是在用 obj c 的话,你可以看看 NSString 的文档,大概就是下面两个方法, string 的编码和解码:
- (nullable instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;
- (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding;
回答:
(NSString )decodeWithUnicode:(NSString)description;
{
description = [description stringByReplacingOccurrencesOfString:@”0x” withString:@”\\”];
NSString *tempstr = [NSString string];
NSArray *studyy =[description componentsSeparatedByString:@”\\u”];
for (NSString *temp in studyy) {
if (temp.length == 4) {
tempstr = [tempstr stringByAppendingString:temp];
}
}
tempstr = [tempstr stringByReplacingOccurrencesOfString:@” ” withString:@””];
NSMutableData *commandToSend= [[NSMutableData alloc] init];
unsigned char whole_byte;
char byte_chars[3] = {‘0′,’0′,’0’};
int i;
for (i=0; i < [tempstr length]/2; i++) {
byte_chars[0] = [tempstr characterAtIndex:i*2];
byte_chars[1] = [tempstr characterAtIndex:i*2+1];
whole_byte = strtol(byte_chars, NULL, 16);
[commandToSend appendBytes:&whole_byte length:1];
}
NSString *unicodeDes = [[NSString alloc]initWithData:commandToSend encoding:(NSUTF16StringEncoding)];
return unicodeDes;
}
@end