views:

379

answers:

3

Hi there.

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 binary output here?);

ÿØÿà

I'd appreciate any help.
Thanks. Ricky.

+4  A: 

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].

Nikolai Ruhe
A: 

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.

Diederik Hoogenboom
That’s not correct. `-[NSString initWithData:]` uses the whole contents of the data object (including zero bytes) and interprets it in the given encoding. Also note that `'\0'` is a defined character in ASCII.
Nikolai Ruhe
But you’re of course right that the method cannot be used to produce a human readable string.
Nikolai Ruhe
+2  A: 

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]];
}
Chuck
I believe, instead of `data[i]` you meant `((unsigned char*)[data bytes])[i]`.
Nikolai Ruhe
More or less. Corrected to be what I thought I'd written in the first place. D'oh.
Chuck
If you already use the performance optimized `stringWithCapacity:` you should calculate the correct capacity: `2 * [data length]`.
Nikolai Ruhe
Sorry Chuck. Thanks for your reply, but you were right in your second line - I am after the binary output as in "01010101". Am I not able to pull that from an NSData object and create a string from it? Thanks, Ricky.
Ricky