开发者

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

开发者 https://www.devze.com 2023-02-16 04:18 出处:网络
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.

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
                                              开发者_JS百科 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..


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

精彩评论

暂无评论...
验证码 换一张
取 消