黑马入学测试—基础—中文编码知识总结

来源:互联网 发布:淘宝宝贝限时打折 编辑:程序博客网 时间:2024/05/22 16:43
为什么要编码呢?在计算机中存储信息的最小单位是1个字节,即8个bit。而我们平时要展现的符号太多,无法用一个字节来完全表示。所以我们构建了一个新的数据结构char,而从char到byte就必须有编码的过程。

在java中是如何编码的。

package net.mpos.lottery.distributorwrs.test;

        /**
         * @author solo
         *
         * @date 2013-9-7
         */
        public class CodeTest {

            public static void toHex(char[] b) {
                for (int i = 0; i < b.length; i++) {
                    System.out.printf("%x " , (int)b[i]);
                }
                System.out.println();
            }

            public static void toHex(byte[] b) {
                for (int i = 0; i < b.length; i++) {
                    System.out.printf("%x " , b[i]);
                }
                System.out.println();
            }

            public static void encode() {
                String name = "I am 中文编码";
                toHex(name.toCharArray());
                try {
                    byte[] iso8859 = name.getBytes("ISO-8859-1");
                    System.out.println("ISO-8859-1:");
                    toHex(iso8859);
                    byte[] gb2312 = name.getBytes("GB2312");
                    System.out.println("GB2312:");
                    toHex(gb2312);
                    byte[] gbk = name.getBytes("GBK");
                    System.out.println("GBK:");
                    toHex(gbk);
                    byte[] utf16 = name.getBytes("UTF-16");
                    System.out.println("UTF-16:");
                    toHex(utf16);
                    byte[] utf8 = name.getBytes("UTF-8");
                    System.out.println("UTF-8:");
                    toHex(utf8);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            public static void main(String[] args) {
                String cn = "I am 中文编码";  // 这里存在编码转换: 将文件存储字节转成unicode存入String对象内存. 采用文件编码

                char[] charArray = cn.toCharArray();
                byte[] data = cn.getBytes();

                System.out.println("print char array : " + cn);
                toHex(cn.toCharArray());

                encode();
            }
        }



例子结果分析
print char array : I am 中文编码
49 20 61 6d 20 4e2d 6587 7f16 7801
49 20 61 6d 20 4e2d 6587 7f16 7801
ISO-8859-1:
49 20 61 6d 20 3f 3f 3f 3f
GB2312:
49 20 61 6d 20 d6 d0 ce c4 b1 e0 c2 eb
GBK:
49 20 61 6d 20 d6 d0 ce c4 b1 e0 c2 eb
UTF-16:
fe ff 0 49 0 20 0 61 0 6d 0 20 4e 2d 65 87 7f 16 78 1
UTF-8:
49 20 61 6d 20 e4 b8 ad e6 96 87 e7 bc 96 e7 a0 81

ISO-8859-1是单字节编码,中文会转化成3f的byte。3f也就是“?”字符。所以出现中文编程“?”的时候很可能就是误用了ISO-8859-1。
GB2312和GBK字符集有一个从char到byte的码表,不同的字码就是从这个码表找到找到与每个字符对应的字节,然后拼装成byte数组。GBK的字符集>GB2312的字符集。所以GBK编码是兼容GB2312的编码的。
UTF-16将char数组放大了一倍。但字节字符在高位补0.
UTF-8对单字节字符仍用1个字节表示,对于汉字采用三个字节表示。
0 0
原创粉丝点击