Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...