为什么byteArray的长度为22而不是20? [英] Why does byteArray have a length of 22 instead of 20?

查看:131
本文介绍了为什么byteArray的长度为22而不是20?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们尝试使用以下Java代码将字符串转换为 Byte []

We try to convert from string to Byte[] using the following Java code:

String source = "0123456789";
byte[] byteArray = source.getBytes("UTF-16");

我们得到一个长度为22个字节的字节数组,我们不知道这个填充来自哪里。
如何获取长度为20的数组?

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?

推荐答案

Alexander的答案解释了为什么它在那里,但不是如何摆脱它。您只需要在编码名称中指定所需的字符串:

Alexander's answer explains 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

这篇关于为什么byteArray的长度为22而不是20?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆