String a="abc";
             byte b[]=a.getBytes();
             System.out.println(b.length);JAVA是用U字符应该是一个字符占的两个字节吧。。
为什么用字母是占一个字节,用中文是两个字节呢???

解决方案 »

  1.   

    JAVA里的char是UNICODE码,占2个字节 
    范围是 '\u0000' 至 '\uffffff' (0 - 65535)
    1—127兼容了ASCII码(高8位都为0) 
    如char a='a';占2个字节, 0x0061
    char b='好';占2个字节,0xbac3。 
    而String.getBytes()方法会忽列ox00,所以打印出来的长度'a'为1而'好'为2
    这些只是个人见解.仅参考。 
      

  2.   

    String.getBytes(),使用平台默认的字符集将此 String 解码为字节序列,并将结果存储到一个新的字节数组中,中文系统默认的是GBK.所以字母占用一个字节。而不是unicode会忽列ox00。
      

  3.   

    为什么是GBK字母只占一个字节呢??
      

  4.   


    import java.io.UnsupportedEncodingException;
    public class EncodeTest {
    /**
    * 打印字符串在指定编码下的字节数和编码名称到控制台
    *
    * @param s
    *字符串
    * @param encodingName
    *编码格式
    */
    public static void printByteLength(String s, String encodingName) {System.out.print("字节数:");try {
    System.out.print(s.getBytes(encodingName).length);} catch (UnsupportedEncodingException e) {
    e.printStackTrace();}System.out.println(";编码:" + encodingName);
    }
    public static void main(String[] args) {String en = "A";String ch = "人";// 计算一个英文字母在各种编码下的字节数System.out.println("英文字母:" + en);EncodeTest.printByteLength(en, "GB2312");EncodeTest.printByteLength(en, "GBK");EncodeTest.printByteLength(en, "GB18030");EncodeTest.printByteLength(en, "ISO-8859-1");EncodeTest.printByteLength(en, "UTF-8");EncodeTest.printByteLength(en, "UTF-16");EncodeTest.printByteLength(en, "UTF-16BE");EncodeTest.printByteLength(en, "UTF-16LE");System.out.println();// 计算一个中文汉字在各种编码下的字节数System.out.println("中文汉字:" + ch);EncodeTest.printByteLength(ch, "GB2312");EncodeTest.printByteLength(ch, "GBK");EncodeTest.printByteLength(ch, "GB18030");EncodeTest.printByteLength(ch, "ISO-8859-1");EncodeTest.printByteLength(ch, "UTF-8");EncodeTest.printByteLength(ch, "UTF-16");EncodeTest.printByteLength(ch, "UTF-16BE");EncodeTest.printByteLength(ch, "UTF-16LE");
    } } 运行结果如下: 英文字母:A 
    字节数:1;编码:GB2312 
    字节数:1;编码:GBK 
    字节数:1;编码:GB18030 
    字节数:1;编码:ISO-8859-1 
    字节数:1;编码:UTF-8 
    字节数:4;编码:UTF-16 
    字节数:2;编码:UTF-16BE 
    字节数:2;编码:UTF-16LE 中文汉字:人 
    字节数:2;编码:GB2312 
    字节数:2;编码:GBK 
    字节数:2;编码:GB18030 
    字节数:1;编码:ISO-8859-1 
    字节数:3;编码:UTF-8 
    字节数:4;编码:UTF-16 
    字节数:2;编码:UTF-16BE 
    字节数:2;编码:UTF-16LE 
    试一下就知道GBK编码中的字母占几个字节