I don’t know how to convert Python’s bitarray to string if it contains non-ASCII bytes. Example:
JavaScript
x
9
1
>>> string='x9f'
2
>>> array=bytearray(string)
3
>>> array
4
bytearray(b'x9f')
5
>>> array.decode()
6
Traceback (most recent call last):
7
File "<stdin>", line 1, in <module>
8
UnicodeDecodeError: 'ascii' codec can't decode byte 0x9f in position 0: ordinal not in range(128)
9
In my example, I just want to somehow get a string ‘x9f’ back from the bytearray. Is that possible?
Advertisement
Answer
In Python 2, just pass it to str()
:
JavaScript
1
9
1
>>> import sys; sys.version_info
2
sys.version_info(major=2, minor=7, micro=8, releaselevel='final', serial=0)
3
>>> string='x9f'
4
>>> array=bytearray(string)
5
>>> array
6
bytearray(b'x9f')
7
>>> str(array)
8
'x9f'
9
In Python 3, you’d want to convert it back to a bytes
object:
JavaScript
1
3
1
>>> bytes(array)
2
b'x9f'
3