2011-02-04 88 views
2

我有一個NSString對象,並希望將其更改爲unichar。是否有可能將NSString轉換爲unichar

int decimal = [[temp substringFromIndex:2] intValue]; // decimal = 12298 

NSString *hex = [NSString stringWithFormat:@"0x%x", decimal]; // hex = 0x300a 

NSString *chineseChar = [NSString stringWithFormat:@"%C", hex]; 

// This statement log a different Chinese char every time I run this code 
NSLog(@"%@",chineseChar); 

當我看到日誌時,每次運行我的代碼時都會給出不同的字符。 m我錯過了什麼......?

回答

5

%C format specifier以16位Unicode字符(unichar)作爲輸入,而不是NSString。你傳遞的是一個NSString,它被重新解釋爲一個整數字符;由於每次運行時字符串都可以存儲在內存中的不同地址處,因此可以將該地址作爲整數來使用,這就是爲什麼每次運行代碼時都會得到不同的中文字符的原因。

在人物只是通過爲整數:

unichar decimal = 12298; 
NSString *charStr = [NSString stringWithFormat:@"%C", decimal]; 
// charStr is now a string containing the single character U+300A, 
// LEFT DOUBLE ANGLE BRACKET 
+0

感謝dude..It就像一個魅力。 – 2011-02-05 11:11:06

相關問題