String s = "中国人 text here";  
byte[] b = s.getBytes("UTF-8");  
            byte[] c = s.getBytes("GBK");  

解决方案 »

  1.   

    字节数组通过编码转换,这个我明白。
    我是不明白在这里:
    在默认的情况下,String构造函数是不是参考ASCII码表?
      

  2.   

    不是。
    看源代码不就知道。
    public String(byte bytes[]) {
            this(bytes, 0, bytes.length);
        }
    public String(byte bytes[], int offset, int length) {
            checkBounds(bytes, offset, length);
            this.value = StringCoding.decode(bytes, offset, length);
        }
      

  3.   

    static char[] decode(byte[] ba, int off, int len) {
            String csn = Charset.defaultCharset().name();
            try {
                // use charset name decode() variant which provides caching.
                return decode(csn, ba, off, len);
            } catch (UnsupportedEncodingException x) {
                warnUnsupportedCharset(csn);
            }
            try {
                return decode("ISO-8859-1", ba, off, len);
            } catch (UnsupportedEncodingException x) {
                // If this code is hit during VM initialization, MessageUtils is
                // the only way we will be able to get any kind of error message.
                MessageUtils.err("ISO-8859-1 charset not available: "
                                 + x.toString());
                // If we can not find ISO-8859-1 (a required encoding) then things
                // are seriously wrong with the installation.
                System.exit(1);
                return null;
            }
        }
      

  4.   

            String str = "ABCD";
            byte[] arr2 = str.getBytes();
            for (byte byt : arr2) {
                System.out.print(byt+"  ");
            }
    结果 65  66  67  68
    猜测ASCII码范围内的字符,不受编码类型的影响。
      

  5.   

    我们常见的很多字符集中,在0~127这个范围也就是最早的ASCII范围内,是和ASCII完全或部分兼容的。
    至少在常见的可见字符(也就是键盘上那些字母,数字,符号),是和ASCII完全兼容的。
    也就是说,这些字符集中,如果遇到二进制的01000001(十进制65,十六进制0x41)这个字节,都代表字母A。具体到GBK来说,它单字节部分,也就是高位(左边)第一个bit是0的,代表这个字符,只占用1个字节完全和ASCII兼容(UTF-8也是类似的方式)
    http://zh.wikipedia.org/wiki/GBK