Objective-C - How can I convert Byte Array to NSString?

[亡魂溺海] 提交于 2020-01-02 20:26:11

问题


I am trying to convert a byte array into a NSString object. 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. I can see in the debugger that the value of serverText is "invalid address". I am new to objective-c but I assume that means the initWithBytes factory method was not successful.

The buffer contains data. Can someone help me out?

Thanks..


回答1:


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


来源:https://stackoverflow.com/questions/5281251/objective-c-how-can-i-convert-byte-array-to-nsstring

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