emoji表情与unicode编码互转的实现(JS,JAVA,C#)

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

emoji表情与unicode编码互转的实现(JS,JAVA,C#)

追极   2021-01-04 我要评论
这篇文章主要介绍了emoji表情与unicode编码互转的实现(JS,JAVA,C#),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前几天刚好有需求要把emoji对应的Unicode编码转换成文字,比如1f601对应的这个笑脸😁,但没有找到C#的把1f601转换成文字的方法,用Encoding.Unicode怎么转换都不对,最后直接复制emoji字符,Visual Studio里面竟然直接显示出来了,那就直接用字符吧,都不用转换了,然后不了了之了。

今天搞Markdown编辑器,由于前面GFM的原因,又对编码进行测试,没查到什么靠谱资料,到时找到很多emoji和Unicode对照表,https://apps.timwhitlock.info/emoji/tables/unicode拿一个笑脸https://apps.timwhitlock.info/unicode/inspect/hex/1F601开刀~

1.表情字符转编码

【C#】

Encoding.UTF32.GetBytes("😁") -> ["1", "f6", "1", "0"]

【js】

"😁".codePointAt(0).toString(16) -> 1f601

【java】

  byte[] bytes = "😀".getBytes("utf-32");
  System.out.println(getBytesCode(bytes));

 private static String getBytesCode(byte[] bytes) {
    String code = "";
    for (byte b : bytes) {
      code += "\\x" + Integer.toHexString(b & 0xff);
    }
    return code;
  }

UTF-32结果一致

【C#】

Encoding.UTF8.GetBytes("😁") -> ["f0", "9f", "98", "81"]

【js】

encodeURIComponent("😁") -> %F0%9F%98%81

UTF-8结果一致

2.编码转表情字符

【js】

String.fromCodePoint('0x1f601')  utf-32

【java】 

 String emojiName = "1f601"; //其实4个字节
  int emojiCode = Integer.valueOf(emojiName, 16);
  byte[] emojiBytes = int2bytes(emojiCode);
  String emojiChar = new String(emojiBytes, "utf-32");
  System.out.println(emojiChar);



  public static byte[] int2bytes(int num){
    byte[] result = new byte[4];
    result[0] = (byte)((num >>> 24) & 0xff);//说明一
    result[1] = (byte)((num >>> 16)& 0xff );
    result[2] = (byte)((num >>> 8) & 0xff );
    result[3] = (byte)((num >>> 0) & 0xff );
    return result;
  }

c# 汉字和Unicode编码互相转换实例

/// <summary>
/// <summary>
/// 字符串转Unicode
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>Unicode编码后的字符串</returns>
public static string String2Unicode(string source)
{
 byte[] bytes = Encoding.Unicode.GetBytes(source);
 StringBuilder stringBuilder = new StringBuilder();
 for (int i = 0; i < bytes.Length; i += 2)
 {
 stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
 }
 return stringBuilder.ToString();
}
 
/// <summary>
/// Unicode转字符串
/// </summary>
/// <param name="source">经过Unicode编码的字符串</param>
/// <returns>正常字符串</returns>
public static string Unicode2String(string source)
{
 return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
   source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
}

参考地址:

https://www.jianshu.com/p/8a416537deb3

https://blog.csdn.net/a19881029/article/details/13511729

https://apps.timwhitlock.info/emoji/tables/unicode

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们