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

We are trying to convert from a string to Byte[] using the following Java code:

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

We get a byte array with a length of 22 bytes, we are not sure where this addition comes from. How to get an array of length 20?

+47
java string encoding bytearray
Oct 23 '08 at 8:45
source share
4 answers

Alexander's answer explains why he is there, but not how to get rid of him. You just need to specify the final target in the encoding name:

 String source = "0123456789"; byte[] byteArray = source.getBytes("UTF-16LE"); // Or UTF-16BE 
+71
Oct 23 '08 at 8:53
source share

The first two bytes can be: "Order byte" . It determines the byte order in each 16-bit word used in the encoding.

+25
23 Oct '08 at 8:50
source share

Try to print the bytes in hexadecimal format to see where the extra 2 bytes are added - are they at the beginning or end?

I choose what you find

+7
Oct 23 '08 at 8:52
source share

At the beginning, UTF has a byte order marker that reports that this stream is encoded in a specific format. As other users have indicated, the 1st byte is 0XFE
2nd byte - 0XFF
other bytes - 0
48
0
49
0
fifty
0
51
0
52
0
53
0
54
0
55
0
56
0
57

+6
Oct 23 '08 at 8:59
source share



All Articles