开发者

Removing junk characters from data

I am doing one project related to socket programming in which from server I get data in which first byte is "9". When I receive this network packet following is the method which is getting fired:

- (void) receivedNetworkPacket:(NSData*)message viaConnection:(Connection*)connection    
{

   NSRange range = NSMakeRange(0,1);
   NSData *lendata = [messa开发者_StackOverflow社区ge subdataWithRange:range];

   NSString *strlen = [[NSString alloc]initWithData:lendata encoding:NSASCIIStringEncoding];
   NSInteger intele = [strlen intValue];
   if ([message length] == intele) {
       NSLog(@"completed");
   }
   else {
       NSLog(@"inprogress");

   }
}

In lendata I am getting the right value but when I try to get it in string I get some junk values like "\b" or "\t". Can I get some help in removing this junk values?


When you say the first byte is "9", are you meaning that the first byte is the character "9" with ASCII code 0x39, or that the first byte is actually 0x09? I suspect the latter, as the byte 0x09 corresponds to tab, commonly abbreviated \t. \b would be the value of 0x08, BTW.

You can get the code value of the byte by doing something like this:

const unsigned char *bytes = (const unsigned char *)[message bytes];
int value;
if (message.length > 0) {
    value = bytes[0];
} else {
    // handle error case here.
}


Your problem probably isn't that you have junk characters -- it's that your string has a certain encoding which you need to adhere to when pulling out the data. What is encoding the data that you are receiving? What is it encoding the string as? (e.g. UTF8, or perhaps a standard Latin encoding, etc.)

If what is being sent over the socket isn't actually a string, it doesn't necessarily make sense to interpret it as a string.

Once you know the encoding, you can create the NSString using this method in the NSString class:

- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜