我试图理解Java中的字符编码。在Java中,使用UTF-16编码将字符存储在16位中。因此,当我将包含6个字符的字符串转换为字节时,我得到了6个字节,而不是我预期的12个字节。我是否忽略了某些概念?
package learn.java;
public class CharacterTest {
public static void main(String[] args) {
String str = "Hadoop";
byte bt[] = str.getBytes();
System.out.println("the length of character array is " + bt.length);
}
}
O/p:字符数组的长度为6
根据@Darshan的说法,尝试使用UTF-16编码获取字节时,结果也不符合预期。
package learn.java;
public class CharacterTest {
public static void main(String[] args) {
String str = "Hadoop";
try{
byte bt[] = str.getBytes("UTF-16");
System.out.println("the length of character array is " + bt.length);
}
catch(Exception e)
{
}
}
}
o/p: the length of character array is 14
utf-16le
或utf-16be
。请参考以下[链接]http://rosettacode.org/wiki/String_length获取更多详细信息。 - Darshan Patel0x76
0x77
,表示接下来的字节使用(默认)大端记法,而不是(备选)小端记法。这种前缀称为字节顺序标记(BOM)。如果没有 BOM,则每个字符将有 12 个字节,每个字符占用两个字节。 - tucuxi