Prateek sharma
Prateek sharma

Reputation: 239

Convert Hex to ASCII number on Objective-c

I have an one hexa decimal number

535443326663315634524877795678586b536854535530342f44526a795744716133353942704359697a6b736e446953677171555473

I want to convert this number to ASCII format which will look like this

STC2fc1V4RHwyVxXkShTSU04/DRjyWDqa359BpCYizksnDiSgqqUTsYUOcHKHNMJOdqR1/TQywpD9a9xhri

i have seen solutions here but none of them is useful to me NSString containing hex convert to ascii equivalent

i checked here but they give different result. Any help

Upvotes: 1

Views: 3064

Answers (2)

TT--
TT--

Reputation: 3205

If you're starting with NSData * you could get the ASCII string this way:

NSData *someData = [NSData dataWithHexString:@"ABC123"];

NSString *asciiString = [[NSString alloc] initWithData: someData encoding:NSASCIIStringEncoding];

Upvotes: 1

Prateek sharma
Prateek sharma

Reputation: 239

This works perfectly

- (NSString *)stringFromHexString:(NSString *)hexString {


    // The hex codes should all be two characters.
    if (([hexString length] % 2) != 0)
        return nil;

    NSMutableString *string = [NSMutableString string];

    for (NSInteger i = 0; i < [hexString length]; i += 2) {

        NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSInteger decimalValue = 0;
        sscanf([hex UTF8String], "%x", &decimalValue);
        [string appendFormat:@"%c", decimalValue];
        NSLog(@"string--%@",string);
    }
    _hexString1=string;

    NSLog(@"string ---%@",_hexString1);
    return string;
}

Upvotes: 1

Related Questions