Convert Hex string to NSString text?

I need to convert an NSString from hexadecimal values ​​to NSString text (ASCII). For example, I need something like:

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

I looked through and changed the code in this thread , but it does not work for me. It works with only one six. Something to do with spaces? Any tips or code examples are greatly appreciated.

+5
source share
3 answers

Well, I will change the same 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);
+8
source

NSScanner, . , .

- (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"]);
+6

In my case, the original string had no delimiters, for example. '303034393934' Here is my solution.

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);
0
source

All Articles