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..
Community
  • 1
  • 1
mm24
  • 9,280
  • 12
  • 75
  • 170

1 Answers1

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

Jiri Zachar
  • 487
  • 3
  • 8