
1 バイト = 8 ビット;
char は Java では 2 バイトです。 Java では、Unicode、2 バイト (16 ビット) を使用して文字を表現します。 最初のバイトはすべて0です。これはスペースの無駄です。
コード例は次のとおりです:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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) {
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;
}
}
|
ログイン後にコピー
実行結果:
以上がJavaのcharは何バイトですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。