Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

objective c - NSString containing hex convert to ascii equivalent

I have an NSString that has hex information such as

<00000020 66747970 4d344120 00000000 4d344120 6d703432 69736f6d 00000000 00031203

which came from NSData. What I need to do is convert that NSString of Hex data to Ascii which would be:

[0][0][0] ftypM4A [0][0][0][0]M4A mp42isom[0][0][0][0][0][3][18][3] 

As you might be able to tell this is a M4A file. I loaded the first part of the file in to NSData using NSFileHandle. I then stored it into NSString:

NSData *data = [filehandle readDataOfLength:1000];
NSString *str = [[NSString alloc]initWithString:[NSString stringWithFormat:@"%@",data]];

Anyone know how to convert NSData directly or convert the NSString to ascii? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you should have done something like this:

NSData *_data = // ... whatever
NSMutableString *_string = [NSMutableString stringWithString:@""];
for (int i = 0; i < _data.length; i++) {
    unsigned char _byte;
    [_data getBytes:&_byte range:NSMakeRange(i, 1)];
    if (_byte >= 32 && _byte < 127) {
        [_string appendFormat:@"%c", _byte];
    } else {
        [_string appendFormat:@"[%d]", _byte];
    }
}
NSLog(@"%@", _string);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...