5

I need to convert an NSString of hex values into an NSString of text (ASCII). 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.

Community
  • 1
  • 1
lreichold
  • 755
  • 12
  • 27

3 Answers3

8

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);
Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105
6

You can use an NSScanner to get each character. 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"]);
ughoavgfhw
  • 39,734
  • 6
  • 101
  • 123
0

In my case, the source string had no separators e.g. '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);
Jim Holland
  • 1,180
  • 12
  • 19