开发者

Converting NSData to an NSString representation is failing

I have an NSData object which I am trying to turn into an NSString using the following line of code:

NSString *theData = [[NSString alloc] initWithData:photo encoding:NSASCIIStringEncoding];

Unfortunately I am getting the following result, instead of my desired binary output (can I expect a b开发者_开发知识库inary output here?);

ÿØÿà

I'd appreciate any help.

Thanks. Ricky.


If you want to transform some arbitrary binary data into a human readable string (for example, of a series of hex values) you are using the wrong method. What you are doing is interpreting the data itself as a string in ASCII encoding.

To simply log the data to a file or to stdout, you can use [theData description].


What you mean by "binary output" is unclear. If you're expecting the string to contain text along the lines of "01010100011110110" or "0x1337abef", you are mistaken about how NSString works. NSString's initWithData:encoding: tries to interpret the data's bytes as though they were the bytes of a string in a particular encoding. It's the opposite of NSString's dataUsingEncoding: — you can call initWithData:encoding: with the result of dataUsingEncoding: and get back the exact same string.

If you want to transform the data into, say, a human-readable string of hex digits, you'll need to do the transformation yourself. You could do something like this:

NSMutableString *binaryString = [NSMutableString stringWithCapacity:[data length]];
unsigned char *bytes = [data bytes];
for (int i = 0; i < [data length]; i++) {
    [binaryString appendFormat:@"%02x", bytes[i]];
}


You cannot parse binary data with the initWithData: method. If you want the hexadecimal string of the contents then you can use the description method of NSData.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜