简体   繁体   中英

Objective C NSData to NSString

I'm learning to develop an iPad Application using cocoaAsyncSocket for my TCP connection.

When i print the NSData into the console, it prints the whole data in hex. When i convert to NSString and prints, it always prints the first byte only.

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {

NSString *msg = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];

NSLog(@"Server Reply data: %@", data);

NSLog(@"Server Reply: %@",msg); }

the print out from console was : "Server Reply data: <4b000230 30303037 33323030 35342020>" "Server Reply: K"

Am i converting it wrongly?

And is it possible to stop when the data reads a ETX(03) in hex for cocoaAsyncsocket? i seen that it is possible to read CRLF.

Thank you.

4b000230 30303037 33323030 35342020 , parsed as UTF8 is the ASCII-compatible code 0x4b (or, 'K') and then a 0x00, which is interpreted as a terminating NULL. So NSString is acting entirely correctly.

Is it possible you're actually receiving UTF16 or some other encoding?

EDIT: if it's just that you're getting two bytes that aren't part of the string (based on the sample in the comments it looks like the length of the entire packet of data, including the two bytes containing the length?) then you can do something like:

NSData *originalData = <whatever came back from the web service>;
NSData *subData = [NSData
                   dataWithBytes:((char *)[originalData bytes]) + 2
                          length:[originalData length] - 2];

That'll cause the data to be copied. You can avoid that if you really want but the semantics get a little more confusing and it's not going to make a measurable difference with a web service in the background.

Hand decoding from the third byte onwards it looks like the stream is:

02  [start of text control code; NSString will render this as ¿]
30  0
30  0
30  0
30  0
37  7
33  3
32  2
30  0
30  0
35  5
34  4
20  [space]
20  [space]

Does that look like the sort of thing you're expecting to find? Given that neither 0x02 or 0x03 will cause the NSString to terminate, if you're confident about the length then I think the easiest thing to do is to remove them after the NSString is created (via stringByReplacingOccurrencesOfString or NSMutableString's replaceOccurrencesOfString:withString:options:range: , saving you from any errors where 0x02 or 0x03 crop up in the byte stream as part of a multi-byte character.

尝试

NSString *aString  = [[NSString alloc] initWithData:aNSData encoding:NSUTF8StringEncoding];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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