How to convert byte array to NSString

I am reading data from a TCP / IP stream and successfully getting an array of bytes from an existing server. Now I am trying to find a way to convert this array to NSString . I have found some examples, but it is difficult for me to get the desired results.

 NSData *data=[[NSMutableData alloc] init]; uint8_t buffer[1024]; unsigned int len=0; len=[(NSInputStream *)stream read:buffer maxLength:1024]; if(len>0){ [data appendBytes:&buffer length:len]; //BYTE ARRAY OBTAINED OK!! /////////////////////////////////////////////////////// //METHOD #1 - Yields 'nil' NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; /////////////////////////////////////////////////////// //METHOD #2 - Log prints OK, but messageString says //'invalid' in debugger, and get warnings all over the //place. I know this is wrong, but it semi-works :) size_t length=[data length]; unsigned char aBuffer[length]; [data getBytes:aBuffer length:length]; aBuffer[length - 1]=0; NSString *messageString =aBuffer; NSLog (@"%s",messageString); /////////////////////////////////////////////////////// }else{ NSLog(@"No Buffer"); } 

Please, help! Any help is provided APPOINTED.

+6
iphone cocoa-touch xcode nsstring
source share
3 answers

I got an answer.

I had to change this:

 NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

For this:

 NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; 
+15
source share

It is not right:

 [data appendBytes:&buffer length:len]; 

It should be:

 [data appendBytes:buffer length:len]; 
+4
source share
 NSString* string = [NSString stringWithUTF8String: data]; 

Make sure your data has zero completion.

-one
source share

All Articles