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

查看:20
本文介绍了为什么 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'sanswer 解释了为什么它在那里,但没有解释如何摆脱它.您只需要在编码名称中指定所需的字节顺序:

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天全站免登陆