Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does byteArray have a length of 22 instead of 20?

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

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?

like image 546
mayaalpe Avatar asked Oct 23 '08 08:10

mayaalpe


People also ask

How do you find the length of a Bytearray?

To find the length of a bytes object in Python, call len() builtin function and pass the bytes object as argument. len() function returns the number of bytes in the object. In the following example, we will take bytes object and find its length using len() function.

What is difference between byte and Bytearray?

bytes and bytearrays are similar... The primary difference is that a bytes object is immutable, meaning that once created, you cannot modify its elements. By contrast, a bytearray object allows you to modify its elements. Both bytes and bytearay provide functions to encode and decode strings.

What does Bytearray mean in Python?

The Python bytearray() function converts strings or collections of integers into a mutable sequence of bytes. It provides developers the usual methods Python affords to both mutable and byte data types.

What is type Bytearray?

The bytearray type is a mutable sequence of integers in the range between 0 and 255. It allows you to work directly with binary data. It can be used to work with low-level data such as that inside of images or arriving directly from the network. Bytearray type inherits methods from both list and str types.


1 Answers

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 
like image 146
Jon Skeet Avatar answered Oct 04 '22 03:10

Jon Skeet