byte[] byteArray = Charset.forName("UTF-8").encode("hello world").array();
System.out.println(byteArray.length);
为什么上面这行代码打印出12,不应该是打印11吗?
最佳答案
数组的长度是 ByteBuffer
容量的大小,它是从但不等于您正在编码的字符数生成的。让我们看一下我们如何为 ByteBuffer
...
如果深入研究 encode()
方法,您会发现 CharsetEncoder#encode(CharBuffer)
看起来像这样:
public final ByteBuffer encode(CharBuffer in)
throws CharacterCodingException
{
int n = (int)(in.remaining() * averageBytesPerChar());
ByteBuffer out = ByteBuffer.allocate(n);
...
根据我的调试器,UTF_8$Encoder
的averageBytesPerChar
是1.1
,输入String
有 11
个字符。 11 * 1.1 = 12.1
,代码在计算时将总数转换为 int
,因此 ByteBuffer
的结果大小为12.
关于java - 在 ByteBuffer 中编码的字符串的长度是多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25941286/