2012-04-22 24 views
0

我收到了来自服务器的一些字节的数据,如下面的方法如何字节数组转换来的NSString或NSMutableArray的

 - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag 
     { 

     \//04 01 00 
NSString *string = [ 
        [NSString alloc] 
        initWithData:data 
        encoding:NSASCIIStringEncoding 
        ]; 
NSLog(string); 

char *ptr = (void *)[data bytes]; // set a pointer to the beginning of your data bytes 

if(*ptr == 0x06) { 
    NSLog(@"okay,.. got a 0x06"); 
} 
ptr++; // go to the next byte 
if(*ptr == 0x05) { 
    NSLog(@"okay,.. got a 0x05"); 
} 
ptr++; 
if(*ptr==0X00){ 
    NSLog(@"okay,.. got a 0X00"); 

} 


//04 01 00 
NSString* newStr = [[NSString alloc] initWithData:data 
             encoding:NSASCIIStringEncoding]; 
/////////////////// 
/////////////////// 
NSLog(@"I received some thing , now trying to read it"); 
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Data Received" message:newStr delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil]; 
[alert show]; 
[alert release]; 

[sock readDataWithTimeout:-1 tag:0]; 
//NSLog(@"Reading %@",newStr); 

}

我可以比较的六值,但无法看到定义UIAlertView因为我认为我无法正确转换,所以请帮助如何转换成NSString和NSMutableArray,以便我可以动态使用它

+0

你期望的UIAlertView中显示?数据的十六进制表示? – 2012-04-22 16:01:29

+0

是的,我也无法看到使用NSLog的数据,我通过硬编码比较数据,我想比较如数组 – Ali 2012-04-22 16:39:46

+0

如果你想看到原始二进制数据的十六进制表示,你需要明确转换它,如[如何将NSData转换为NSString十六进制字符串?](http://stackoverflow.com/questions/7520615/how-to-convert-an-nsdata-into-an-nsstring-hex-string ) – 2012-04-22 16:43:51

回答

0

我没有尝试你的代码,但并非所有的ascii字符都可以视觉呈现。尝试使用ASCII码> 32的一些代码,查找字母或数字。或者将字符作为十进制或六进制数字回显。

0

试试这个,

NSString* newStr = [[NSString alloc] initWithData:data 
            encoding:NSUTF8StringEncoding]; 
相关问题