简体   繁体   English

如何将字节数组转换为NSString

[英]How to convert byte array to NSString

I am reading data from a TCP/IP stream and am successfully receiving a byte array from the pre-existing server. 我正在从TCP / IP流读取数据,并已成功从现有服务器接收字节数组。 I am now trying to find a way to convert that array to an NSString . 我现在正在尝试寻找一种将该数组转换为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. 非常感谢提供的任何帮助。

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

This is wrong: 这是错误的:

[data appendBytes:&buffer length:len];

It should be: 它应该是:

[data appendBytes:buffer length:len];
NSString* string = [NSString stringWithUTF8String: data];

显然,请确保您的数据以null结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM