0

I have a NSdata object that is populated with a bunch of information thats formated in hex.. I am trying to convert it into its proper string representation but am struggling to have any success.

One thing I have tried is to simply put it into a NSString and then NSLog it with a special character identifier thingy.. forgot the word (%02x), However to do this I am encoding it to NSUTF16.. which i dont want to do.. I mearly want to see exactly whats the data I am getting looks like as a NSString.

The reason I am doing this is because I am having some issues with my encoding later on in my code and im not sure if its because the data I am receiving is incorrect or me stuffing it up at some point when I am handling it.

Any help would be appreciated.

HurkNburkS
  • 5,492
  • 19
  • 100
  • 183

3 Answers3

1

You can get a string representation of your NSData like so:

NSData *data = (your data)
NSString *string = [NSString stringWithCString:[data bytes] encoding:NSUTF8StringEncoding];

Does that answer your question?

Joe Hankin
  • 950
  • 8
  • 15
0

Maybe I haven't understood, but something like this:

NSData *yourData;
NSLog(@"%@", [yourData description]);

doesn't fit your need?

Michele Percich
  • 1,872
  • 2
  • 14
  • 20
  • hrmm trying now, I read something about 'description' but couldnt find how to use it in the dev docs. – HurkNburkS Oct 25 '12 at 21:30
  • Nope this dosnt fit my need.. its showing me the data in its hex format I would like to translate that so i can read exactly what it says. – HurkNburkS Oct 25 '12 at 21:32
0

Give this a try -

-(NSString*)hexToString:(NSData*)data{
    NSString *hexString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    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:@"%d", decimalValue];
    }

    return string;
}
yeesterbunny
  • 1,847
  • 2
  • 13
  • 17
  • Hrmm.. so the more reading I do, I think I have found out that although the data represents HEX.. its actually UNICODE encoded.. but still HEX so now im trying to figure out how to encode it straight to UTF16 – HurkNburkS Oct 25 '12 at 22:24