字符集
常见字符集介绍
- 标准ASCII字符集
ASCII(American Standard Code for Information Interchange): 美国信息交换标准代码,包括了英文、符号等。标准ASCII使用1个字节存储一个字符,首尾是0,总共可表示128个字符,对美国佬来说完全够用。 - GBK(汉字内码扩展规范,国标)
汉字编码字符集,包含了2万多个汉字等字符,GBK中一个中文字符编码成两个字节的形式存储。
注意:GBK兼容了ASCII字符集。 - Unicode字符集(统一码,也叫万国码)
Unicode是国际组织制定的,可以容纳世界上所有文字、符号的字符集。四个字节表示一个字符. - UTF-8
是Unicode字符集的一种编码方案,采取可变长编码方案,共分四个长度区:1个字节,2个字节,3个字节,4个字节
英文字符、数字等只占1个字节(兼容标准ASCII编码),汉字字符占用3个字节。
要点
ASCII字符集:只有英文、数字、符号等,占1个字节。
GBK字符集:汉字占2个字节,英文、数字占1个字节。
UTF-8字符集:汉字占3个字节,英文、数字占1个字节。
字符集的编码、解码操作
String编码:把文字符号变成数字数据
byte[] getBytes():使用平台的默认字符集将该 String编码为一系列字节,将结果存储到新的字节数组中
byte[] getBytes(String charsetName):使用指定的字符集将该 String编码为一系列字节,将结果存储到新的字节数组中
String解码:把数字数据解析成文字符号
String(byte[] bytes):通过使用平台的默认字符集解码指定的字节数组来构造新的String
String(byte[] bytes, String charsetName):通过指定的字符集解码指定的字节数组来构造新的String
//1.需求:将"abc"进行编码
byte[] bys1 = "abc".getBytes();
byte[] bys2 = "abc".getBytes("GBK");
System.out.println(Arrays.toString(bys1));
System.out.println(Arrays.toString(bys2));
System.out.println("-------------------");
//2.需求:将"黑马程序员"进行编码
byte[] bys3 = "黑马程序员".getBytes();
byte[] bys4 = "黑马程序员".getBytes("gbk");
System.out.println(Arrays.toString(bys3));
System.out.println(Arrays.toString(bys4));
System.out.println("-------------------");
//3.需求:将bys3解码(编码和解码方案一致)
String str1 = new String(bys3);
System.out.println(str1);
//编码和解码方案不一致(会乱码!)
String str2 = new String(bys3, "gbk");
System.out.println(str2);
//4.需求:将bys4解码
String str3 = new String(bys4, "gbk");
System.out.println(str3);
}
[97, 98, 99]
[97, 98, 99]
-------------------
[-23, -69, -111, -23, -87, -84, -25, -88, -117, -27, -70, -113, -27, -111, -104]
[-70, -38, -62, -19, -77, -52, -48, -14, -44, -79]
-------------------
黑马程序员
榛戦┈绋嬪簭鍛�
黑马程序员
Process finished with exit code 0