编码
字符集
字符集定义了文字或符号和二进制的对应关系,为字符分配了唯一的编号。常见的字符集有ASCII字符集、GBxxx系列(GBK)字符集、Unicode(UTF-8)字符集,在几乎所有的字符集中,常用字符的编号往往比较小,罕见字符的编号往往比较大。目前的 Unicode 字符集已经收录了上百万的字符,至少需要三个字节才能容纳下所有的字符编号。
字符编码
字符编码规定了以何种方式将文字或符号的编号存储到内存中。
字符串编码与解码
-
使用平台默认字符集将字符串编码为一系列字节,再通过平台默认的字符集解码指定的字节数组来构造新的字符串。
public class Demo { public static void main(String[] args) throws UnsupportedEncodingException { byte[] bytes = "西琳".getBytes(); String s = new String(bytes); System.out.println(s); System.out.println(bytes.length); } } ---*--- 输出结果: 西琳 4 //一个字符占两个字节
-
使用指定字符集将字符串编码为一系列字节,再通过指定的字符集解码指定的字节数组来构造新的字符串。
public class Demo { public static void main(String[] args) throws UnsupportedEncodingException { byte[] bytes = "西琳".getBytes("GBK"); String s = new String(bytes,"GBK"); System.out.println(s); System.out.println(bytes.length); } } ---*--- 输出结果: 西林 6 //一个字符占三个字节
参考资料:https://blog.youkuaiyun.com/guxiaonuan/article/details/78678043