2013-03-02 141 views
0

我的NSData這樣的:如何將此NSData轉換爲NSString?

455a4f4e 00000001 01020304 00000000 00000000 

我的代碼:

Byte bytes[] = {0x45, 0x5a, 0x4f, 0x4e, 0, 0, 0, 1, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0}; 
NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)]; 
NSString *str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; 
NSLog(@"%@", str); // prints "EZON" 

我希望得到的結果是EZON0001等等

爲什麼打印結果不包括後面的數字'EZON'?

回答

4

由於0x4e之後的零不是ASCII/UTF-8數字'0',而是字符串標記的結尾。它應該是爲0x30,不爲0x00 ...

+1

+1好的解釋答案:) – 2013-03-02 03:33:20

+0

非常感謝你! – withshe 2013-03-02 03:46:29

+0

確保在字節數組的末尾爲空終止符保留一個0。 – rmaddy 2013-03-02 03:47:06

0

試試這個

Byte bytes[] = {0x45, 0x5a, 0x4f, 0x4e, 0, 0, 0, 1, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0}; 
    NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)]; 
    NSString* newStr = [NSString stringWithUTF8String:[data bytes]]; 
    NSLog(@"%@", newStr); 
+0

問題是提供了字符「0 0 0 1」等的錯誤字節。其餘的代碼很好。 – rmaddy 2013-03-02 03:40:54

+0

@ravindhiran:無需回答,當你看到有4個upvotes的答案時,除非你看到你可以給予更好。 – 2013-03-02 03:47:22

+0

感謝您的回覆,但您的回答不正確。 – withshe 2013-03-02 03:47:58