0

I got an NSString containing a hex value which I would like to convert in ASCII. How can I do this?

NSString * hexString = // some value NSString * asciiString = // ? convert hexString to ASCI somehow 

INCORRECT APPROACH THAT I TRIED:

I tried the following approach that I found on a similar question but it did not work for me:

 NSData *_data = [hexString dataUsingEncoding:NSUTF8StringEncoding]; NSMutableString *_string = [NSMutableString stringWithString:@""]; for (int i = 0; i < _data.length; i++) { unsigned char _byte; [_data getBytes:&_byte range:NSMakeRange(i, 1)]; if (_byte >= 32 && _byte < 127) { [_string appendFormat:@"%c", _byte]; } else { [_string appendFormat:@"[%d]", _byte]; } } asciiString = _string; // Still shows the same as before.. 

1 Answer 1

2

this works for me:

NSString * str = @"312d4555"; NSMutableString * newString = [[NSMutableString alloc] init]; int i = 0; while (i < [str length]){ NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)]; int value = 0; sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value); [newString appendFormat:@"%c", (char)value]; i+=2; } NSLog(@"%@", newString); 

output is: hello

Sign up to request clarification or add additional context in comments.

1 Comment

"hello" is @"68656c6c6f" in UTF-8

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.