java中的char占幾個字節(jié)實例分析
1:“字節(jié)”是byte,“位”是bit ;
2: 1 byte = 8 bit ;
char 在Java中是2個字節(jié)。java采用unicode,2個字節(jié)(16位)來表示一個字符。
例子代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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; } } |
運行結(jié)果:
bytes 大小:3
bytes1大小:2
java是用unicode來表示字符,"中"這個中文字符的unicode就是2個字節(jié)。
String.getBytes(encoding)方法是獲取指定編碼的byte數(shù)組表示,
通常gbk/gb2312是2個字節(jié),utf-8是3個字節(jié)。
如果不指定encoding則取系統(tǒng)默認的encoding。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/ocean20/article/details/6743385