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

时间:2014-10-31 23:59:31

标签: ios objective-c decode

我有一个带有十六进制字符串的NSString,例如“ترقب”这意味着“ترقب”。

现在我想将十六进制字符串转换为另一个显示“ترقب”的NSString对象。怎么做?

2 个答案:

答案 0 :(得分:0)

您的字符串看起来像HTML转义序列,除了#'之后的空格。如果这真的是你所拥有的(检查一些东西并不只是将Unicode显示为转义),那么有很多方法可以转换它。您可以只处理字符串,挑选出六角形字符并从中生成UniChar值等等。

如果你想要一个高级的,可能有些冗长的方法,你可以尝试:

- (NSString *)decodeHTMLescapes:(NSString *)raw
{
   NSString *nospaces = [raw stringByReplacingOccurrencesOfString:@" " withString:@""]; // one way to remove the spaces
   const char *cString = [nospaces UTF8String]; // C string
   NSData *bytes = [[NSData alloc] initWithBytesNoCopy:(void *)cString length:strlen(cString) freeWhenDone:NO]; // as bytes
   NSAttributedString *attributed = [[NSAttributedString alloc] initWithHTML:bytes documentAttributes:nil]; // interpret as HTML
   NSString *decoded = attributed.string; // and finally as plain text
   return decoded;
}

(a)剥离空格,(b)创建一个C字符串,(c)创建一个字节缓冲区,这样我们就可以(d)将该字节缓冲区解释为HTML,并且(e)最终得到字符串背部。使用initWithBytesNoCopy:length:freeWhenDone:是为了减少复制所有这一切。

使用它像:

NSString *raw = @"&# x62a;&# x631;&# x642;&# x628;";
NSString *decoded = [self decodeHTMLescapes:raw];
NSLog(@"%@ -> %@", raw, decoded);

HTH

答案 1 :(得分:0)

- (NSMutableString *) hextostring:(NSString *) str{
    //ت
    NSMutableString *string = [[NSMutableString alloc]init];

    str = [str stringByReplacingOccurrencesOfString:@"&#" withString:@"0"];
    str = [str stringByReplacingOccurrencesOfString:@" " withString:@"z;"];
    NSArray *arr = [str componentsSeparatedByString:@";"];

    for (int i =0; i<[arr count]; i++) {
        if ([[arr objectAtIndex:i] isEqualToString:@"z"]) {
            [string appendString:@" "];
        } else {
            unsigned x;

            [[NSScanner scannerWithString: [arr objectAtIndex:i]] scanHexInt: &x];
            [string appendFormat:@"%C",(unichar)x];
        }
    }

    NSLog(@"%@",string);
    return string;
}