I need to convert an ASCII string into a list of bits and vice versa:
str = "Hi" -> [0,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1] [0,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1] -> "Hi"
Strings can be converted to lists using list() .
You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.
To convert a string to list of characters in Python, use the list() method to typecast the string into a list. The list() constructor builds a list directly from an iterable, and since the string is iterable, you can construct a list from it.
Method#1: Using split() method The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.
There are many ways to do this with library functions. But I am partial to the third-party bitarray
module.
>>> import bitarray >>> ba = bitarray.bitarray()
Conversion from strings requires a bit of ceremony. Once upon a time, you could just use fromstring
, but that method is now deprecated, since it has to implicitly encode the string into bytes. To avoid the inevitable encoding errors, it's better to pass a bytes
object to frombytes
. When starting from a string, that means you have to specify an encoding explicitly -- which is good practice anyway.
>>> ba.frombytes('Hi'.encode('utf-8')) >>> ba bitarray('0100100001101001')
Conversion to a list is easy. (Also, bitstring objects have a lot of list-like functions already.)
>>> l = ba.tolist() >>> l [False, True, False, False, True, False, False, False, False, True, True, False, True, False, False, True]
bitstring
s can be created from any iterable:
>>> bitarray.bitarray(l) bitarray('0100100001101001')
Conversion back to bytes or strings is relatively easy too:
>>> bitarray.bitarray(l).tobytes().decode('utf-8') 'Hi'
And for the sake of sheer entertainment:
>>> def s_to_bitlist(s): ... ords = (ord(c) for c in s) ... shifts = (7, 6, 5, 4, 3, 2, 1, 0) ... return [(o >> shift) & 1 for o in ords for shift in shifts] ... >>> def bitlist_to_chars(bl): ... bi = iter(bl) ... bytes = zip(*(bi,) * 8) ... shifts = (7, 6, 5, 4, 3, 2, 1, 0) ... for byte in bytes: ... yield chr(sum(bit << s for bit, s in zip(byte, shifts))) ... >>> def bitlist_to_s(bl): ... return ''.join(bitlist_to_chars(bl)) ... >>> s_to_bitlist('Hi') [0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1] >>> bitlist_to_s(s_to_bitlist('Hi')) 'Hi'
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