简体   繁体   English

将十六进制字符串转换为文本的 NSString?

[英]Convert String of Hex to NSString of text?

I need to convert an NSString of hex values into an NSString of text (ASCII).我需要将十六进制值的 NSString 转换为文本(ASCII)的 NSString。 For example, I need something like:例如,我需要类似的东西:

"68 65 78 61 64 65 63 69 6d 61 6c" to be "hexadecimal"

I have looked at and tweaked the code in this thread , but it's not working for me.我已经查看并调整了这个线程中的代码,但它对我不起作用。 It is only functional with one hex pair.它仅适用于一对十六进制对。 Something to do with the spaces?和空格有关系吗? Any tips or sample code is extremely appreciated.非常感谢任何提示或示例代码。

Well I will modify the same thing for your purpose.好吧,我会为你的目的修改同样的东西。

NSString * str = @"68 65 78 61 64 65 63 69 6d 61 6c";
NSMutableString * newString = [NSMutableString string];

NSArray * components = [str componentsSeparatedByString:@" "];
for ( NSString * component in components ) {
    int value = 0;
    sscanf([component cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
    [newString appendFormat:@"%c", (char)value];
}

NSLog(@"%@", newString);

You can use an NSScanner to get each character.您可以使用NSScanner来获取每个字符。 The spaces will be necessary to separate each value, or the scanner will continue scanning and ignore other data.需要空格来分隔每个值,否则扫描仪将继续扫描并忽略其他数据。

- (NSString *)hexToString:(NSString *)string {
    NSMutableString * newString = [[NSMutableString alloc] init];
    NSScanner *scanner = [[NSScanner alloc] initWithString:string];
    unsigned value;
    while([scanner scanHexInt:&value]) {
        [newString appendFormat:@"%c",(char)(value & 0xFF)];
    }
    string = [newString copy];
    [newString release];
    return [string autorelease];
}

// called like:
NSLog(@"%@",[self hexToString:@"68 65 78 61 64 65 63 69 6d 61 6c"]);

In my case, the source string had no separators eg '303034393934' Here is my solution.就我而言,源字符串没有分隔符,例如'303034393934' 这是我的解决方案。

NSMutableString *_string = [NSMutableString string];
for (int i=0;i<12;i+=2) {
    NSString *charValue = [tagAscii substringWithRange:NSMakeRange(i,2)];
    unsigned int _byte;
    [[NSScanner scannerWithString:charValue] scanHexInt: &_byte];
         if (_byte >= 32 && _byte < 127) {
             [_string appendFormat:@"%c", _byte];
          } else {
             [_string appendFormat:@"[%d]", _byte];
          }
}
NSLog(@"%@", _string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM