标签:
几点注意:
1,ASCII码和ISO-8859-1都是单字节编码,ASCII码能表示128个字符,ISO-8859-1总共能表示256个字符。都不能表示中文,如果中文字符或其它不在IOS-8859码值范围内的字符会统一用3f表示(显示为"?", 通常所说的"黑洞");
2,GBK兼容GB2312,是双字节编码,GB2312包含6763个汉字,GBK包含21003个汉字;
3,UTF-16为定长双字节编码,大大简化了字符串的操作,但是会浪费存储空间。JAVA以UTF-16作为内存存储格式(见编码测试输出source行);
4,UTF-8采用变长,不同类型的字符可以由1~6个字节组成(汉字一般3个字节)。UTF-8规则如下:
测试代码:
package com.test.main; public class TestCode { public static void encode(){ String name = "淘!我喜欢!"; toHex(name.toCharArray()); String [] codeType = {"ISO-8859-1", "GB2312", "GBK", "UTF-16", "UTF-8"}; for (String type : codeType) { try { byte [] bytes = name.getBytes(type); toHex(type, bytes); } catch (Exception e) { e.printStackTrace(); } } } private static void toHex(String name, byte[] charArray) { System.out.print(String.format("%-15s", name + ":")); for (int i = 0; i < charArray.length; i++) { System.out.print(String.format("%-4x ", charArray[i])); } System.out.println(); } private static void toHex(char[] charArray) { System.out.print(String.format("%-15s","source:")); for (int i = 0; i < charArray.length; i++) { System.out.print(String.format("%-4x ", (int)charArray[i])); } System.out.println(); } public static void main(String[] args) { encode(); } }
输出:
标签:
原文地址:http://www.cnblogs.com/cookiehu/p/5097359.html