2012-04-22 30 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]; 
相關問題