7

I don't know how to convert Python's bitarray to string if it contains non-ASCII bytes. Example:

>>> string='\x9f'
>>> array=bytearray(string)
>>> array
bytearray(b'\x9f')
>>> array.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x9f in position 0: ordinal not in range(128)

In my example, I just want to somehow get a string '\x9f' back from the bytearray. Is that possible?

2
  • Is this Python 2 or 3? Commented Dec 26, 2014 at 13:08
  • Python 2. I will add it in the question. Commented Dec 26, 2014 at 13:09

4 Answers 4

13

In Python 2, just pass it to str():

>>> import sys; sys.version_info
sys.version_info(major=2, minor=7, micro=8, releaselevel='final', serial=0)
>>> string='\x9f'
>>> array=bytearray(string)
>>> array
bytearray(b'\x9f')
>>> str(array)
'\x9f'

In Python 3, you'd want to convert it back to a bytes object:

>>> bytes(array)
b'\x9f'
Sign up to request clarification or add additional context in comments.

1 Comment

Oh. That was it. Simple. (I'm still new in python!)
9

Did you try

byteVariable.decode('utf-8')

Comments

5

I'd like to mention the binascii library that comes with Python.

My use case: I was querying a database that had a binary field being used as a key within the DB. I wanted to pull that binary field and treat it as a key elsewhere. I thought converting it to a string was the best use-case.

binascii offered me a better alternative:

import binascii binary_field = bytearray(b'\x92...') binascii.hexlify(binary_field)

1 Comment

The binascii module is very useful.
0

use bytes(array, encoding='utf8')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.