Convert unicode

前端 未结 3 1981
眼角桃花
眼角桃花 2021-01-15 12:48

I have a UITextField to enter a unicode value , when i tap a UIButton need to convert it and showing in a UILabel.
Th

3条回答
  •  无人及你
    2021-01-15 13:20

    0D05 is just a hexadecimal number. You can use NSScanner to parse the hexadecimal string into an integer, and then create a NSString containing the Unicode character.

    NSString *hexString = yourInputField.text;
    
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    uint32_t unicodeInt;
    if ([scanner scanHexInt:&unicodeInt]) {
        unicodeInt = OSSwapHostToLittleInt32(unicodeInt); // To make it byte-order safe
        NSString *unicodeString = [[NSString alloc] initWithBytes:&unicodeInt length:4 encoding:NSUTF32LittleEndianStringEncoding];
        yourOutputLabel.text = unicodeString;
    } else {
        // Conversion failed, invalid input.
    }
    

    This works even with Unicodes > U+FFFF, such as 1F34C (thanks to R. Martinho Fernandes for his feedback).

提交回复
热议问题