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!
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