How to convert NData populated with hex values to NSString

╄→尐↘猪︶ㄣ 提交于 2019-12-25 04:58:19

问题


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.


回答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?




回答2:


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

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

doesn't fit your need?




回答3:


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


来源:https://stackoverflow.com/questions/13077136/how-to-convert-ndata-populated-with-hex-values-to-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!