How to convert a unichar value to an NSString in Objective-C?

前端 未结 5 1407
无人及你
无人及你 2020-11-29 00:32

I\'ve got an international character stored in a unichar variable. This character does not come from a file or url. The variable itself only stores an unsigned short(0xce91)

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 01:20

    Since 0xce91 is in the UTF-8 format and %C expects it to be in UTF-16 a simple solution like the one above won't work. For stringWithFormat:@"%C" to work you need to input 0x391 which is the UTF-16 unicode.

    In order to create a string from the UTF-8 encoded unichar you need to first split the unicode into it's octets and then use initWithBytes:length:encoding.

    unichar utf8char = 0xce91; 
    char chars[2];
    int len = 1;
    
    if (utf8char > 127) {
        chars[0] = (utf8char >> 8) & (1 << 8) - 1;
        chars[1] = utf8char & (1 << 8) - 1; 
        len = 2;
    } else {
        chars[0] = utf8char;
    }
    
    NSString *string = [[NSString alloc] initWithBytes:chars
                                                length:len 
                                              encoding:NSUTF8StringEncoding];
    

提交回复
热议问题