[英]One Char is Two Bytes in Java?
In java, one char is two bytes.在 java 中,一个字符是两个字节。
But, why below code return 2, not 4?但是,为什么下面的代码返回 2 而不是 4?
public static void main(String[] args) {
byte[] b = new String(new char[] {'H', 'I' }).getBytes();
System.out.println(b.length);
}
getBytes()
encodes the Unicode characters in the default Charset
of the JVM, usually ISO-8859-1
or UTF-8
, both of which uses a single byte to store those characters. getBytes()
在 JVM 的默认Charset
对 Unicode 字符进行编码,通常是ISO-8859-1
或UTF-8
使用单个字节来存储这些字符。
This code should help illustrate what's going on:这段代码应该有助于说明发生了什么:
public static void main(String[] args) throws Exception {
test("ISO-8859-1", new char[] { 'H', 'I' });
test("UTF-8" , new char[] { 'H', 'I' });
test("UTF-16LE" , new char[] { 'H', 'I' });
test("UTF-32LE" , new char[] { 'H', 'I' });
test("ISO-8859-1", new char[] { '⅓', '⅔' });
test("UTF-8" , new char[] { '⅓', '⅔' });
test("UTF-16LE" , new char[] { '⅓', '⅔' });
test("UTF-32LE" , new char[] { '⅓', '⅔' });
test("UTF-8" , "😀👍");
test("UTF-16LE" , "😀👍");
test("UTF-32LE" , "😀👍");
}
static void test(String charsetName, char[] chars) throws Exception {
test(charsetName, new String(chars));
}
static void test(String charsetName, String input) throws Exception {
byte[] bytes = input.getBytes(charsetName);
System.out.printf("%-12s %-6s", charsetName, new String(bytes, charsetName));
for (byte b : bytes)
System.out.printf(" %02x", b);
System.out.println();
}
Output Output
ISO-8859-1 HI 48 49
UTF-8 HI 48 49
UTF-16LE HI 48 00 49 00
UTF-32LE HI 48 00 00 00 49 00 00 00
ISO-8859-1 ?? 3f 3f
UTF-8 ⅓⅔ e2 85 93 e2 85 94
UTF-16LE ⅓⅔ 53 21 54 21
UTF-32LE ⅓⅔ 53 21 00 00 54 21 00 00
UTF-8 😀👍 f0 9f 98 80 f0 9f 91 8d
UTF-16LE 😀👍 3d d8 00 de 3d d8 4d dc
UTF-32LE 😀👍 00 f6 01 00 4d f4 01 00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.