xcode 如何将字节数组转换为 NSString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/738674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert byte array to NSString
提问by Dutchie432
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.
我正在从 TCP/IP 流中读取数据,并成功地从预先存在的服务器接收到一个字节数组。我现在正试图找到一种方法将该数组转换为NSString
. 我找到了几个例子,但很难得到我想要的结果。
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.
请帮忙!非常感谢提供的任何帮助。
回答by Dutchie432
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];
回答by Chris Lundie
This is wrong:
这是错误的:
[data appendBytes:&buffer length:len];
It should be:
它应该是:
[data appendBytes:buffer length:len];
回答by Andrew Grant
NSString* string = [NSString stringWithUTF8String: data];
Make sure your data is null-terminated, obviously.
显然,确保您的数据以空值结尾。