1

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

6
  • have you tried the solution on the other thread? If yes, could you include that code here? Commented Sep 16, 2013 at 12:18
  • It seems like you want Base64 encoding. Check out stackoverflow.com/questions/882277/… Commented Sep 16, 2013 at 12:23
  • @robbie_c tried that last one , but result is different what iam getting here in branah.com/ascii-converter Commented Sep 16, 2013 at 12:32
  • NTM1NDQzMzI2NjYzMzE1NjM0NTI0ODc3Nzk1Njc4NTg2YjUzNjg1NDUzNTUzMDM0MmY0NDUyNmE3OTU3NDQ3MTYxMzMzNTM5NDI3MDQzNTk2OTdhNmI3MzZlNDQ2OTUzNjc3MTcxNTU1NDczN , its coming like this .. it should start with STC Commented Sep 16, 2013 at 12:38
  • Ah fair enough, that website seems to just convert one byte of the hex number to one ASCII character, the answer given should work. Commented Sep 16, 2013 at 13:09

2 Answers 2

1

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; } 
Sign up to request clarification or add additional context in comments.

Comments

1

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]; 

3 Comments

That doesn't work out of the box because dataWithHexString is not a function provided by Foundation. You need to add the code from NSData+HexString.m (opensource.apple.com/source/Security/Security-55471/…)
Ok, good point. Btw why does the link have comment // Not efficent ?
Perhaps because of the use of subroutines such as strtol() and the way the source string is indexed. One could access the input as a raw char array instead, which is probably faster, and convert the nibbles thru a table or a few comparisons, additions and shifts. But it's fast enough for most uses as you'll probably not convert millions of these per second.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.