Java 为什么 byteArray 的长度是 22 而不是 20?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/228987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does byteArray have a length of 22 instead of 20?
提问by mayaalpe
We try to convert from string to Byte[]
using the following Java code:
我们尝试从字符串转换为Byte[]
使用以下 Java 代码:
String source = "0123456789";
byte[] byteArray = source.getBytes("UTF-16");
We get a byte array of length 22 bytes, we are not sure where this padding comes from. How do I get an array of length 20?
我们得到一个长度为 22 字节的字节数组,我们不确定这个填充来自哪里。如何获得长度为 20 的数组?
采纳答案by Jon Skeet
Alexander's answerexplains why it's there, but not how to get rid of it. You simply need to specify the endianness you want in the encoding name:
亚历山大的回答解释了为什么它在那里,但没有解释如何摆脱它。您只需要在编码名称中指定所需的字节顺序:
String source = "0123456789";
byte[] byteArray = source.getBytes("UTF-16LE"); // Or UTF-16BE
回答by Alexander
May be the first two bytes are the Byte Order Mark. It specifies the order of bytes in each 16-bit word used in the encoding.
可能前两个字节是Byte Order Mark。它指定编码中使用的每个 16 位字中的字节顺序。
回答by Bevan
Try printing out the bytes in hex to see where the extra 2 bytes are added - are they at the start or end?
尝试以十六进制打印出字节以查看添加了额外 2 个字节的位置 - 它们是在开头还是结尾?
I'm picking that you'll find a byte order markerat the start (0xFEFF) - this allows anyone consuming (receiving) the byte array to recognise whether the encoding is little-endian or big-endian.
我选择你会在开头找到一个字节顺序标记(0xFEFF)——这允许任何使用(接收)字节数组的人识别编码是小端还是大端。
回答by anjanb
UTF has a byte order marker at the beginning that tells that this stream is encoded in a particular format. As the other users have pointed out, the
1st byte is 0XFE
2nd byte is 0XFF
the remaining bytes are
0
48
0
49
0
50
0
51
0
52
0
53
0
54
0
55
0
56
0
57
UTF 在开头有一个字节顺序标记,表明此流是以特定格式编码的。正如其他用户所指出的,第
一个字节是 0XFE
第二个字节是 0XFF
其余字节是
0
48
0
49
0
50
0
51
0
52
0
53
0
54
0
55
0
56
0
57