[英]Objective-C - How can I convert Byte Array to NSString?
I am trying to convert a byte array into a NSString
object. 我正在尝试将字节数组转换为NSString
对象。 For testing purposes I am then just trying to print out the contents of the string to the log. 为了进行测试,我只是试图将字符串的内容打印到日志中。
Here's what I got: 这是我得到的:
UInt8 buf[BUFSIZE];
CFIndex bytesRead = CFReadStreamRead(stream, buf, BUFSIZE);
if (bytesRead > 0) {
NSString *serverText = [[NSString alloc] initWithBytes:buf
length:(NSUInteger)BUFSIZE
encoding:NSASCIIStringEncoding];
NSLog("%@",serverText);
[serverText release];
I am trying to initialize a new NSString
using initWithBytes
and store this in serverText
. 我正在尝试使用initWithBytes
初始化一个新的NSString
并将其存储在serverText
。 I can see in the debugger that the value of serverText
is "invalid address". 我可以在调试器中看到serverText
值为“无效地址”。 I am new to objective-c but I assume that means the initWithBytes
factory method was not successful. 我是Objective-c的新手,但我认为这意味着initWithBytes
工厂方法未成功。
The buffer contains data. 缓冲区包含数据。 Can someone help me out? 有人可以帮我吗?
Thanks.. 谢谢..
Here what I came up with: 这是我想出的:
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];
}
NSString *serverText = [[NSString alloc]
initWithData:data
encoding:NSASCIIStringEncoding];
NSLog(@"%@", serverText);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.