Java中char是unicode 佔幾個位元組呢?
阿新 • • 發佈:2019-02-12
1:“位元組”是byte,“位”是bit ;
2: 1 byte = 8 bit ;
char 在java中是2個位元組。java採用unicode,2個位元組(16位)來表示一個字元。
例子程式碼如下:
[java] view plaincopyprint?- publicclass Test {
- publicstaticvoid 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);
- }
- publicstatic
- byte[] b = newbyte[2];
- b[0] = (byte) ((c & 0xFF00) >> 8);
- b[1] = (byte) (c & 0xFF);
- return b;
- }
- }
執行結果:
bytes 大小:3
bytes1大小:2
java是用unicode來表示字元,"中"這個中文字元的unicode就是2個位元組。
String.getBytes(encoding)方法是獲取指定編碼的byte陣列表示,
通常gbk/gb2312是2個位元組,utf-8是3個位元組。
如果不指定encoding則取系統預設的encoding。