Home > Blockchain >  How can I combine multiple lists of separated bit values into strings?
How can I combine multiple lists of separated bit values into strings?

Time:07-09

I have a list of lists containing 32 individual bits. I want to separate these values into 4 strings of binary digits, each representing a byte.

My data looks like:

array = [[1, 0, 0, 0, 1, 0, 1, 0],
         [0, 1, 1, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 1, 0, 0, 0],
         [0, 0, 1, 1, 1, 0, 1, 1]]

The result should satisfy

array[0] == '10001010'
array[1] == '01100000'
array[2] == '00001000'
array[3] == '00111011'

Every solution I've tried leaves me with a string containing commas, such as '1,0,0,0,1,0,1,0'.

What is the simplest way to take each of these byte groupings and convert them into a string?

CodePudding user response:

Use a list comprehension to iterate the items, and join each item by converting it to a string:

>>> array = [[1, 0, 0, 0, 1, 0, 1, 0],
...          [0, 1, 1, 0, 0, 0, 0, 0],
...          [0, 0, 0, 0, 1, 0, 0, 0],
...          [0, 0, 1, 1, 1, 0, 1, 1]]
>>> array = [''.join(str(n) for n in item) for item in array]
>>> array
['10001010', '01100000', '00001000', '00111011']

CodePudding user response:

Try this:

arr1, arr2, arr3, arr4 = [''.join(map(str,elem)) for elem in arr]
print(arr1, arr2, arr3, arr4, sep='\n')

10001010
01100000
00001000
00111011

or without tuple unpacking:

arr = ["".join(map(str, elem)) for elem in arr]
print(arr)
['10001010', '01100000', '00001000', '00111011']

Then you can access them with arr[0] etc..

  • Related