Literal converstion NSData to NSString [closed]

2019-09-30 06:31发布

问题:

I am new to iOS programming and i am trying to get a textual representation of an NSData object as a NSString

For example if the NSData object is:

<07010013 01020000 09000100 000199c2>

I want to convert that to:

"070100130102000009000100000199c2"

How can I do that?

回答1:

HINT#1 //general answer

NSString provides an initializer for this purpose. You can see more info using the docs here.

NSString * str = [[NSString alloc] initWithData: mynsdata 
                                      encoding:NSUTF8StringEncoding];

Assuming you use ARC.

HINT#2 // the answer for hex nsdata

int len = [mynsdata length];
NSMutableString *str = [NSMutableString stringWithCapacity:len*2];
const unsigned char *nsdata_bytes = [mynsdata bytes];
for (int i = 0; i < len; ++i) {
    [str appendFormat:@"%02x", nsdata_bytes[i]];
}