欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-11-16 16:32:46|栏目:JAVA代码|点击:

前几天刚好有需求要把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

上一篇:Java乱码问题解决方法_动力节点Java学院整理

栏    目:JAVA代码

下一篇:SpringBoot中时间格式化的五种方法汇总

本文标题:emoji表情与unicode编码互转的实现(JS,JAVA,C#)

本文地址:http://www.codeinn.net/misctech/183722.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有