2012-03-27 106 views
6

如何轉換十六進制值成表情符號圖標,我有一個字符串像下面的iOS轉換十六進制數值

NSString *myVal = @"1F61E"; 

我如何轉換這個文本,以顯示它的表情符號charrcaters?

我發現,價值from this link 請讓我知道,我真的卡住了這個問題

Updated

NSString *utf8String1 = @"1F61E"; 
NSString *a = [self convert:utf8String1]; 
NSLog(@"%@ &&&&&&&&&&&&&&&&&&&&&",a); 


-(NSString*)convert:(NSString*)decoded{ 

    unichar unicodeValue = (unichar) strtol([decoded UTF8String], NULL, 16); 
    char buffer[2]; 
    int len = 1; 

    if (unicodeValue > 127) { 
     buffer[0] = (unicodeValue >> 8) & (1 << 8) - 1; 
     buffer[1] = unicodeValue & (1 << 8) - 1; 
     len = 2; 
    } else { 
     buffer[0] = unicodeValue; 
    } 

    return [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding]; 



} 
+0

檢查所以這個答案,解釋正是這一點: http://stackoverflow.com/questions/1775859/how-to-convert-a- unichar-value-to-nsstring-in-objective-c – 2012-03-27 11:27:22

回答

4

您嘗試編碼的代碼點不適合16位。因此,你需要使用UTF-32編碼:

NSScanner *scan = [[NSScanner alloc] initWithString:@"1F61E"]; 
unsigned int val; 
[scan scanHexInt:&val]; 
char cc[4]; 
cc[3] = (val >> 0) & 0xFF; 
cc[2] = (val >> 8) & 0xFF; 
cc[1] = (val >> 16) & 0xFF; 
cc[0] = (val >> 24) & 0xFF; 
NSString *s = [[NSString alloc] 
    initWithBytes:cc 
      length:4 
     encoding:NSUTF32StringEncoding]; 
NSLog(@"[%@]", s); 
+0

謝謝你的答覆。我可以嗎?將我的變量轉換爲這種格式0x00,0x01,0cf6,0x1e?請讓我知道 – user198725878 2012-03-27 13:15:22

+0

@ user198725878請參閱我的編輯。 – dasblinkenlight 2012-03-27 13:20:08

+0

非常感謝您的幫助,請幫我解釋一下它是如何工作的 – user198725878 2012-03-28 03:32:01

0

的第一步是將其轉換爲它的數值:

unichar unicodeValue = (unichar) strtol([input UTF8String], NULL, 16); 

然後,按照規則th是post

char buffer[2]; 
int len = 1; 

if (unicodeValue > 127) { 
    buffer[0] = (unicodeValue >> 8) & (1 << 8) - 1; 
    buffer[1] = unicodeValue & (1 << 8) - 1; 
    len = 2; 
} else { 
    buffer[0] = unicodeValue; 
} 

return [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding]; 

你現在有你的UTF-8格式化字符串!

+0

嗨,謝謝你的答覆。這個nsstring的結果會是表情符號圖標嗎?或者我還需要做些什麼才能顯示出來.pls讓我知道 – user198725878 2012-03-27 12:05:20

+0

@ user198725878對不起,我沒有一個設備來測試它,你必須自己嘗試! – 2012-03-27 12:06:26

+0

當我試圖打印返回nsstring值使用nslog它只是顯示我爲「(null)」請讓我知道 – user198725878 2012-03-27 12:18:56