How to convert byte array to NSString

余生颓废 提交于 2019-12-03 05:20:02

问题


I am reading data from a TCP/IP stream and am successfully receiving a byte array from the pre-existing server. I am now trying to find a way to convert that array to an NSString. I have found several examples, but am having a hard time getting my 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 assistance provided is GREATLY appreciated.


回答1:


I got the answer.

I had to change this:

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

To this:

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



回答2:


This is wrong:

[data appendBytes:&buffer length:len];

It should be:

[data appendBytes:buffer length:len];



回答3:


NSString* string = [NSString stringWithUTF8String: data];

Make sure your data is null-terminated, obviously.



来源:https://stackoverflow.com/questions/738674/how-to-convert-byte-array-to-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!