JAVA各种编码所占用的字节数

闲来无事,研究了一下几种常用的编码格式所占用的字节数。写了一个小工程大家一目了然,话不多说上代码。

String str = "于先森ABC";
        byte[] bytes1 = str.getBytes("gbk");
        System.out.print("gbk: ");
        for (byte b : bytes1) {
            System.out.print(Integer.toHexString(b&0xff)+" ");
        }

        byte [] bytes2 = str.getBytes("utf-8");
        System.out.print("\rutf-8 : ");
        for (byte b : bytes2) {
            System.out.print(Integer.toHexString(b&0xfff)+" ");
        }


        byte [] bytes3 = str.getBytes("utf-16be");
        System.out.print("\rutf-16be: ");
        for (byte b : bytes3) {
            System.out.print(Integer.toHexString(b&0xfff)+" ");
        }


        byte [] bytes4 = str.getBytes("iso-8859-1");
        System.out.print("\riso-8859-1: ");
        for (byte b : bytes4) {
            System.out.print(Integer.toHexString(b&0xfff)+" ");
        }


        byte [] bytes5 = str.getBytes("utf-16le");
        System.out.print("\rutf-16le: ");
        for (byte b : bytes5) {
            System.out.print(Integer.toHexString(b&0xfff)+" ");
        }

        byte [] bytes6 = str.getBytes("us-ascii");
        System.out.print("\rus-ascii: ");
        for (byte b : bytes6) {
            System.out.print(Integer.toHexString(b&0xfff)+" ");
        }

接下来看输出结果:

gbk: d3 da cf c8 c9 ad 41 42 43
utf-8 : fe4 fba f8e fe5 f85 f88 fe6 fa3 fae 41 42 43
utf-16be: 4e f8e 51 48 68 fee 0 41 0 42 0 43
iso-8859-1: 3f 3f 3f 41 42 43
utf-16le: f8e 4e 48 51 fee 68 41 0 42 0 43 0
us-ascii: 3f 3f 3f 41 42 43
\

由此可以看出 iso-8859-1 与 us-ascii都是一个中文只占用一个字节。
而utf-16be,utf-16le不管中英文都是1个字符均占用两个字节。区别是be的最高低址存放最高位字节,而le却是最高地址存放最高位字节。
utf-8更是一个中文字符占用3个字节。

此致,敬礼。感谢观看!

你可能感兴趣的:(java,编码)