1:“字节”是byte,“位”是bit ;

  2: 1 byte = 8 bit ;

  char 在Java中是2个字节。java采用unicode,2个字节(16位)来表示一个字符。

  例子代码如下:

 

 

[java] view plain copy

 
 print?
1. public class Test {  
2.   
3.   
4. public static void main(String[] args) {  
5. "中";  
6. char x ='中';  
7. byte[] bytes=null;  
8. byte[] bytes1=null;  
9. try {  
10. "utf-8");  
11.             bytes1 = charToByte(x);  
12. catch (UnsupportedEncodingException e) {  
13. // TODO Auto-generated catch block  
14.             e.printStackTrace();  
15.         }  
16. "bytes 大小:"+bytes.length);  
17. "bytes1大小:"+bytes1.length);  
18.     }  
19. public static byte[] charToByte(char c) {   
20. byte[] b = new byte[2];   
21. 0] = (byte) ((c & 0xFF00) >> 8);   
22. 1] = (byte) (c & 0xFF);   
23. return b;   
24.     }  
25. }  
 
 
运行结果:
bytes 大小:3
bytes1大小:2

  

java是用unicode来表示字符,"中"这个中文字符的unicode就是2个字节。

 String.getBytes(encoding)方法是获取指定编码的byte数组表示,

通常gbk/gb2312是2个字节,utf-8是3个字节

如果不指定encoding则取系统默认的encoding。