2013-07-18 28 views
0

我試圖將一行十六進制轉換爲一行char值。這是我使用的代碼:NULL值繼續終止我的NSString

// Store HEX values in a mutable string: 
    NSUInteger capacity = [data length] * 2; 
    NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:capacity]; 
    const unsigned char *dataBuffer = [data bytes]; 
    NSInteger i; 
    for (i=0; i<[data length]; ++i) { 
     [stringBuffer appendFormat:@"%02X ", (NSUInteger)dataBuffer[i]]; 
    } 
// Log it: 
    NSLog(@"stringBuffer is %@",stringBuffer); 


// Convert string from HEX to char values: 
NSMutableString * newString = [[NSMutableString alloc] init]; 
NSScanner *scanner = [[NSScanner alloc] initWithString:content]; 
unsigned value; 
while([scanner scanHexInt:&value]) { 
    [newString appendFormat:@"%c ",(char)(value & 0xFF)]; 
} 
NSLog(@"newString is %@", newString); 

這個很好,迄今爲止。輸出收到它如預期:

String Buffer is 3D 3E 2C 01 2C 31 33 30 37 31 38 30 39 32 34 2D 30 37 2C FF 00 00 00 00 00 
newString is = > , , 1 3 0 7 1 8 0 9 2 4 - 0 7 , ˇ 

只有一個問題,NULL值終止我的字符串(我認爲)。新字符串應該輸入「0 0 0 0」,但不是,它只是在那裏結束。我認爲它在那裏結束,因爲一行中的3個零= char中的NULL。有誰知道我可以如何防止這個字符串終止並顯示整個值?

回答

1

%c格式不會產生NULL字符的任何輸出,但 也不會終止字符串。請看下面的例子:

NSMutableString * newString = [[NSMutableString alloc] init]; 
[newString appendFormat:@"%c", 0x30]; // the '0' character 
[newString appendFormat:@"%c", 0x00]; // the NULL character 
[newString appendFormat:@"%c", 0x31]; // the '1' character 
NSLog(@"newString is %@", newString); 
// Output: newString is 01 
NSLog(@"length is %ld", newString.length); 
// Output: length is 2 

所以你不能指望得到十六進制輸入00任何輸出。特別是,您不能 期望得到字符「0」,因爲它具有十六進制的30而不是00的ASCII碼。

請注意,您可以轉換NSDataNSString直接使用

NSString *s = [[NSString alloc] initWithData:data encoding:encoding]; 

如果data代表了一些編碼,例如一個字符串UTF-8(與您的數據不同的是 )。

如果您解釋數據所代表的內容以及所需數據的字符串表示形式,則可能有更好的答案。

+0

我明白了。當我檢查輸出時,字符串沒有終止。 00的空格表示。你是馬丁的男人,謝謝。 – John

+0

@John:不客氣! –