栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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编码互相转换实例
/// 
/// 
/// 字符串转Unicode
/// 
/// 源字符串
/// Unicode编码后的字符串
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();
}
 
/// 
/// Unicode转字符串
/// 
/// 经过Unicode编码的字符串
/// 正常字符串
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

到此这篇关于emoji表情与unicode编码互转的实现(JS,JAVA,C#)的文章就介绍到这了,更多相关emoji表情与unicode编码互转内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/129618.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号