小编典典
在UTF-16版本中,由于插入了一个标记来区分Big Endian(默认)和Little
Endian,因此获得14个字节。如果指定UTF-16LE,则将获得12个字节(小尾数,不添加字节顺序标记)。
编辑- 使用此程序查看由不同编码生成的实际字节:
public class Test {
public static void main(String args[]) throws Exception {
// bytes in the first argument, encoded using second argument
byte[] bs = args[0].getBytes(args[1]);
System.err.println(bs.length + " bytes:");
// print hex values of bytes and (if printable), the char itself
char[] hex = "0123456789ABCDEF".toCharArray();
for (int i=0; i
int b = (bs[i] < 0) ? bs[i] + 256 : bs[i];
System.err.print(hex[b>>4] + "" + hex[b&0xf]
+ ( ! Character.isISOControl((char)b) ? ""+(char)b : ".")
+ ( (i%4 == 3) ? "\n" : " "));
}
System.err.println();
}
}
例如,以UTF-8运行时(在其他JVM默认编码下,FE和FF的字符显示会有所不同),输出为:
$ javac Test.java && java -cp . Test hello UTF-16
12 bytes:
FEþ FFÿ 00. 68h
00. 65e 00. 6Cl
00. 6Cl 00. 6Fo
和
$ javac Test.java && java -cp . Test hello UTF-16LE
10 bytes:
68h 00. 65e 00.
6Cl 00. 6Cl 00.
6Fo 00.
和
$ javac Test.java && java -cp . Test hello UTF-16BE
10 bytes:
00. 68h 00. 65e
00. 6Cl 00. 6Cl
00. 6Fo
2020-11-13