如題,本文就不說啥了,直接上代碼:
static async Task Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
try
{
stopwatch.Start();
Console.OutputEncoding = Encoding.Unicode;
var json = await File.ReadAllTextAsync("static/emoji/face-smiling.json");
var emojis = JsonOperator.ToObject<FaceSmilingDto>(json);
foreach (var emoji in emojis.FaceSmiling)
{
Console.Write(Emoji.EmojiCodeToUTF16String(emoji.Code));
}
Console.WriteLine($"\nElapsed time:{stopwatch.ElapsedMilliseconds}ms");
stopwatch.Stop();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (stopwatch.IsRunning)
stopwatch.Stop();
Console.WriteLine("end");
}
}
emoji處理
public class Emoji
{
/// <summary>
/// 字符串形式的 Emoji 16進制Unicode編碼 轉換成 UTF16字符串 能夠直接輸出到客戶端
/// </summary>
/// <param name="emojiCode"></param>
/// <returns></returns>
public static string EmojiCodeToUTF16String(string emojiCode)
{
if (emojiCode.Length != 4 && emojiCode.Length != 5)
{
throw new ArgumentException("錯誤的 EmojiCode 16進制數據長度.一般爲4位或5位");
}
// 1f604
int emojiUnicodeHex = int.Parse(emojiCode, System.Globalization.NumberStyles.HexNumber);
// 1f604對應 utf16 編碼的int
int emojiUTF16Hex = EmojiToUTF16(emojiUnicodeHex, true); // 這裏字符的低位在前.高位在後.
var emojiBytes = BitConverter.GetBytes(emojiUTF16Hex); // 把整型值變成Byte[]形式. Int64的話 丟掉高位的空白0000000
return Encoding.Unicode.GetString(emojiBytes);
}
private static Int32 EmojiToUTF16(int v, bool lowHeight = true)
{
int vx = v - 0x10000;
int vh = vx >> 10; // 取高10位部分
int vl = vx & 0x3ff; // 取低10位部分
int wh = 0xD800; // 結果的前16位元初始值,這個地方應該是根據Unicode的編碼規則總結出來的數值.
int wl = 0xDC00; // 結果的後16位元初始值,這個地方應該是根據Unicode的編碼規則總結出來的數值.
wh = wh | vh;
wl = wl | vl;
if (lowHeight)
{
return wl << 16 | wh; // 低位左移16位以後再把高位合併起來 得到的結果是UTF16的編碼值 // 適合低位在前的操作系統
}
else
{
return wh << 16 | wl; // 高位左移16位以後再把低位合併起來 得到的結果是UTF16的編碼值 // 適合高位在前的操作系統
}
}
}
運行結果: