Skip to content Skip to sidebar Skip to footer

Convert Binary String To Bytes

I have a string that is made up of byte values 0-255. I need to convert it to a bytearray. I do not want to transform range 128-255 to utf-8 – in fact, the string is already enco

Solution 1:

The latin-1 codec (aka latin_1, iso-8859-1, iso8859-1, 8859, cp819, latin, latin1, and L1) is a 1-to-1 encoding encoding each Unicode ordinal from 0 to 255 to an equivalent byte value. Assuming your string contains no ordinals above 255, it should work for your purposes.

Solution 2:

The following code works for me and create a array of bytes:

In [1]: import array

In [2]: string="ABCDÄ…"

In [3]: array.array('B',string.encode('utf-8'))
Out[3]: array('B', [65, 66, 67, 68, 196, 133])

Post a Comment for "Convert Binary String To Bytes"