如何将表情符号转换为其UTF-32 /转义的unicode?

Jok*_*_37 3 c# unicode wpf emoticons emoji

我正在使用WPF中的聊天应用程序,但我想在其中使用表情符号。我正在使用WPF应用程序。我想阅读来自Android / iOS设备的表情符号并显示相应的图像。

在WPF上,我得到一个黑色表情 这个。我以某种方式得到了一个表情符号图标库,它们分别以十六进制/转义的unicode值保存。因此,我想将这些表情符号转换成UTF-32 /转义的unicode,以便我可以直接用它们替换相关的表情图标。

我曾尝试将表情符号转换为其unicode,但最终得到带有几个符号的不同字符串,而这些符号具有不同的unicode。

string unicodeString = "\u1F642";  // represents  

Encoding unicode = Encoding.Unicode;
byte[] unicodeBytes = unicode.GetBytes(unicodeString);

char[] unicodeChars = new char[unicode.GetCharCount(unicodeBytes, 0, unicodeBytes.Length)];
unicode.GetChars(unicodeBytes, 0, unicodeBytes.Length, unicodeChars, 0);
string asciiString = new string(unicodeChars);
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏!

Ran*_*dom 6

转义的Unicode字符串在C#中无效。

string unicodeString = "\u1F642";  // represents  
Run Code Online (Sandbox Code Playgroud)

这段代码不代表“略带笑容的脸”,因为C#仅尊重前4个字符-代表UTF-16(带有2个字节)。

因此,您实际上得到的是代表字母的字母,1F64后跟一个简单的2http://www.fileformat.info/info/unicode/char/1f64/index.htm

所以这: ?2

如果要用4个字节键入十六进制并获取相应的字符串,则必须使用:

var unicodeString = char.ConvertFromUtf32(0x1F642);
Run Code Online (Sandbox Code Playgroud)

https://msdn.microsoft.com/zh-CN/library/system.char.convertfromutf32(v=vs.110).aspx

或者你可以这样写:

\uD83D\uDE42
Run Code Online (Sandbox Code Playgroud)

然后可以像这样解析该字符串,以获得所需的结果,该结果还是我们开始的十六进制值:

var x = char.ConvertFromUtf32(0x1F642);

var enc = new UTF32Encoding(true, false);
var bytes = enc.GetBytes(x);
var hex = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
    hex.AppendFormat("{0:x2}", bytes[i]);
}
var o = hex.ToString();
//result is 0001F642
Run Code Online (Sandbox Code Playgroud)

(由于UTF-32始终为4字节,因此结果带有前导零(0)。

除了for循环,您还可以使用BitConverter.ToString(byte[]) https://msdn.microsoft.com/zh-cn/library/3a733s97(v=vs.110).aspx,结果将如下所示:

var x = char.ConvertFromUtf32(0x1F642);

var enc = new UTF32Encoding(true, false);
var bytes = enc.GetBytes(x);
var o = BitConverter.ToString(bytes);
//result is 00-01-F6-42
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的答案。让我困惑的一点是 \uD83D\uDE42 来自哪里。为了向其他人澄清,这些被称为“代理对”。您可以在这里找到更多信息:https://unicodebook.readthedocs.io/unicode_encodings.html。它本质上是将 UTF-32 转换为两个 UTF-16 值的结果。可以在这里找到一个简单的转换工具:http://trigeminal.fmsinc.com/16to32AndBack.asp (4认同)