2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > 编码:UTF-8编码 UTF-16编码规则

编码:UTF-8编码 UTF-16编码规则

时间:2022-10-26 07:30:55

相关推荐

编码:UTF-8编码 UTF-16编码规则

UTF是"Unicode/UCS Transformation Format"的首字母缩写,即把Unicode字符转换为某种格式之意。

凡是以UTF开头的字符编码方式都是用来实现编码表示unicode字符的。

UTF-8和UTF-16都是可变长度的编码方式:

UTF-8编码方案可能用1、2、3或4个字节表示一个unicode值。UTF-16编码方案可能用2或4个字节表示一个unicode值。

UTF-32是定长的编码方式,用4个字节表示一个unicode值,不用的位全为0。

UTF-8具体编码方式看这篇:/xuejianbest/article/details/85049748

UTF-16要相对简单些:/wiki/UTF-16

为方便理解上面的编码过程,下面是我用Java实现的辅助平面的unicode字符串表示到utf-16字符串表示的代码:

import java.io.UnsupportedEncodingException;public class Test {public static void main(String[] args) throws Exception {System.out.println(h("\\u277CC")); // \ud85d\udfccSystem.out.println("\ud85d\udfcc"); // ?}public static String h(String s) throws UnsupportedEncodingException {int h1 = 0xd800;int h2 = 0xdc00;Integer value = Integer.valueOf(s.substring(2), 16) - 0x10000;String bstr = Integer.toBinaryString(value);String bstrpad = bstr;for (int i = 20; i > bstr.length(); i--) {bstrpad = "0" + bstrpad;}int i1 = Integer.valueOf(bstrpad.substring(0, 10), 2) + h1;int i2 = Integer.valueOf(bstrpad.substring(10), 2) + h2;byte[] bs = new byte[4];bs[0] = (byte) (i1 >> 8 & 0xFF);bs[1] = (byte) (i1 & 0xFF);bs[2] = (byte) (i2 >> 8 & 0xFF);bs[3] = (byte) (i2 & 0xFF);System.out.println(new String(bs, "utf-16")); // 打印此unicode表示的对应字符。本例子调用时会打印'?'return String.format("\\u%x\\u%x", i1, i2); // 返回其utf-16-be的代理对的字符串表示}}

对于汉字的编码顺序:

Unicode是按部首排序的。GBK编码是按读音排序的。

可以通过这个网站查询unicode编码表:https://unicode-/cn/

如对𧟌这个字的查询结果(可以看到utf-8编码是不用考虑字节序的,而utf-16和utf-32都需要):

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。