stfxc
stfxc

Reputation: 174

How to convert bitarray data to string in Python

I have binary code in bitarray. I want to display the contents of the bitarray, as a string. How can I fix the code to display the content.

from bitarray import bitarray
data = bitarray('010101')
print(str(data))

My output:

bitarray('010101')

I need:

010101

Upvotes: 1

Views: 2228

Answers (2)

blue-zircon
blue-zircon

Reputation: 316

You can use

print(data.to01())

Upvotes: 1

lmiguelvargasf
lmiguelvargasf

Reputation: 69933

Besides method .to01, you can also use decodetree which will allow you to specify what you want to use instead of 0 and instead of 1:

>> from bitarray import bitarray, decodetree
>> t = decodetree({'0': bitarray('0'), '1': bitarray('1')})
>> data = bitarray('010101')
>>> ''.join(data.decode(t))
010101

For more info about .to01, decode and other methods/functions, see the docs for bitarray here.

Upvotes: 1

Related Questions