java中的char占幾個字節


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.         String str= "中";  
  6.         char x ='中';  
  7.         byte[] bytes=null;  
  8.         byte[] bytes1=null;  
  9.         try {  
  10.             bytes = str.getBytes("utf-8");  
  11.             bytes1 = charToByte(x);  
  12.         } catch (UnsupportedEncodingException e) {  
  13.             // TODO Auto-generated catch block  
  14.             e.printStackTrace();  
  15.         }  
  16.         System.out.println("bytes 大小:"+bytes.length);  
  17.         System.out.println("bytes1大小:"+bytes1.length);  
  18.     }  
  19.     public static byte[] charToByte(char c) {   
  20.         byte[] b = new byte[2];   
  21.         b[0] = (byte) ((c & 0xFF00) >> 8);   
  22.         b[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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM