Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 947
lreichold Avatar asked Jun 29 '11 03:06

lreichold


2 Answers

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);
like image 162
Deepak Danduprolu Avatar answered Oct 05 '22 23:10

Deepak Danduprolu


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"]);
like image 25
ughoavgfhw Avatar answered Oct 06 '22 00:10

ughoavgfhw