lreichold
lreichold

Reputation: 765

Convert String of Hex to NSString of text?

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.

Upvotes: 5

Views: 7450

Answers (3)

Jim Holland
Jim Holland

Reputation: 1225

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

Upvotes: 0

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

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

Upvotes: 8

ughoavgfhw
ughoavgfhw

Reputation: 39905

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

Upvotes: 6

Related Questions