0

below is my method for Hex to ASCII conversion

-(NSString*)getASCIIString:(NSString*)strHex
{
    NSMutableString *strAscii = [NSMutableString string];
    for (int i=0;i<24;i+=2) {
        NSString *charValue = [strHex substringWithRange:NSMakeRange(i,2)];
        unsigned int _byte;
        [[NSScanner scannerWithString:charValue] scanHexInt: &_byte];
        if (_byte >= 32 && _byte < 127) {
            [strAscii appendFormat:@"%c", _byte];
        } else {
            [strAscii appendFormat:@"[%d]", _byte];
        }
    }
    NSLog(@"Hex: %@", strHex);
    NSLog(@"Ascii: %@", strAscii);
    return strAscii;
}

Above methode convert Hex String to ASCII but i notice for one scenario giving me wrong result as below:

strHex : 4E4932313533000000000066 Ascii : NI2153[0][0][0][0][0]f (Wrong)

why for 00 i am getting [0]. ?

my method work perfectly fine , only when there is 00 in Hex string as i mentioned i am getting [0] in Ascii string.

Please Let me know tested perfect conversion method.

Wenfang Du
  • 8,804
  • 9
  • 59
  • 90
user2813740
  • 517
  • 1
  • 7
  • 29
  • maybe [this](https://stackoverflow.com/questions/6421282/how-to-convert-hex-to-nsstring-in-objective-c) is what you looking for? – Tj3n Aug 03 '17 at 07:31
  • no my method work perfectly fine , only when there is 00 in Hex string as i mentioned i am getting [0] in Ascii string. it should not be .... – user2813740 Aug 03 '17 at 07:33
  • According to your code the output is correct since a zero byte (hex `0x0)` is a non-printable character and not in the range 32 .. 127. Don't mix it up with the *letter* 0 which is hex `0x30` – vadian Aug 03 '17 at 07:56

1 Answers1

1

If the hex string is 00, you get the value 0 in _byte, and thus you are in the else branch, and get [0] as result for [strAscii appendFormat:@"[%d]", _byte];.

clemens
  • 16,716
  • 11
  • 50
  • 65