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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With