Java中char到底是多少字节

如题所述

java中的char占2个字节 
       1:“字节”是byte,“位”是bit ;
  2: 1 byte = 8 bit ;
  char 在java中是2个字节。java采用unicode,2个字节(16位)来表示一个字符。
代码如下:

public class Test {
    public static void main(String[] args) {
        String str= "中";
        char x ='中';
        byte[] bytes=null;
        byte[] bytes1=null;
        try {
            bytes = str.getBytes("utf-8");
            bytes1 = charToByte(x);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("bytes å¤§å°ï¼š"+bytes.length);
        System.out.println("bytes1大小:"+bytes1.length);
    }
    public static byte[] charToByte(char c) { 
        byte[] b = new byte[2]; 
        b[0] = (byte) ((c & 0xFF00) >> 8); 
        b[1] = (byte) (c & 0xFF); 
        return b; 
    }
}
结果如下:
bytes 大小:3
bytes1大小:2
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-09-13
char是2个字节的。str是个字符串,所以getBytes是需要得到一个0结尾的字符串,所以就是3个字节了。
第2个回答  2016-11-08
Wow!It's so heavy Lulu tried several times,
相似回答
大家正在搜