Ricky
Ricky

Reputation: 309

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

ÿØÿà

I'd appreciate any help.
Thanks. Ricky.

Upvotes: 1

Views: 3048

Answers (3)

Chuck
Chuck

Reputation: 237010

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]];
}

Upvotes: 2

diederikh
diederikh

Reputation: 25271

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.

Upvotes: 0

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81856

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

Upvotes: 4

Related Questions