NSString containing hex convert to ascii equivalent

試著忘記壹切 提交于 2019-11-26 23:24:14

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/15276620/nsstring-containing-hex-convert-to-ascii-equivalent

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