problem reading hex values from file with NSString or NSData
I have a file which I need to grab some data from but I am only getting nil wh开发者_StackOverflowen i read it.
the file contains
K vU™"3Dô U0?*
the hex values are
1B 1B 01 1B 4B 07 20 1B 76 02 06 55 AA 11 22 33 44 99 20 0A 1B 55 30 1B 1B 3F 0C 1B 2A 01 0C 0C
I have tried reading the file a few ways but always get nil when i turn it into a string.
NSData *textData = [[NSData alloc] initWithContentsOfFile:filename];
NSLog(@"%@",[textData description]);
//prints out <1b1b011b 4b07201b 76020655 aa112233 4499200a 1b55301b 1b3f0c1b 2a010c0c>
text = [[NSString alloc] initWithData:textData encoding:NSUTF8StringEncoding];
//at this point text is nil
text = [[NSString alloc] initWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:err];
//at this point text is still nil
text = [NSString stringWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:err];
//at this point text is still nil
I know its reading the file. I can print out the attributes and see it says the size is 30. what did i miss/what am i doing wrong?
Your file is probably simply not encoded in UTF8. That's why trying to interpret the data into some UTF8 string fails.
Are you sure it is not UTF-16 (LE or BE) or any other encoding? (or maybe simply ASCII -- with some non-printable characters)
How about text = [[NSString alloc] initWithString:[textData description]];
? :)
精彩评论