Centurion
Centurion

Reputation: 14304

How to convert properly from NSData to NSString?

I'm getting weird NSString value after performing a conversion. For example, I have one byte with value 2 (00000010) that is stored in response. I tried both NSString initWithData and initWithBytes but both return weird symbol (upside down question mark). Here's my code:

NSString *command1 = [[NSString alloc] initWithData:response encoding:NSASCIIStringEncoding];
NSString *command2 = [[NSString alloc] initWithBytes:[response bytes] length:[response length] encoding:NSASCIIStringEncoding];

NSLog(@"command1: %@", command1);
NSLog(@"command2: %@", command2);

Also tried NSUTF8StringEncoding but NSASCIIStringEncoding is correct one because data comes encoded one byte per symbol.

Upvotes: 0

Views: 1545

Answers (2)

JeremyP
JeremyP

Reputation: 86651

ASCII is not necessarily the right encoding. ASCII only defines characters between 0x00 and 0x7F. If response is an HTTP response, and the encoding is not specified in the HTTP Content-Type header, the default is ISO-8859-1 for which you should use NSISOLatin1StringEncoding

And it doesn't matter what encoding you use: control characters (0x00 - 0x1F) aren't necessarily printable.

Upvotes: 1

Richard J. Ross III
Richard J. Ross III

Reputation: 55563

From what I am reading, this is what you want:

NSString *stringWithContentsOfBinaryData(NSData *data)
{
    NSMutableString *output;

    int len = [data length];
    uint8_t *bytes = [data bytes];
    for (int i = 0; i < len; i++)
    {
        [output appendFormat:@"%i", bytes[i]];
    } 

    return output;
}

It just simply converts each byte to it's integer representation and concatenates that into a string.

Upvotes: 1

Related Questions