Home > Mobile >  How to append binary value into an array?
How to append binary value into an array?

Time:03-01

I pull random binary from a source and I am trying to append each binary bytes into an array. However, Python only append each character into the array and not each binary bytes. I tried to search in here and Google and it seems there is no prior example that I could follow. I wonder if anybody know?

I have this list of 16 binary bytes random_byte_request:

10001100 11001010 11111101 11010100 01101010 01011001 00010000 10111110 01111000 11111010 00100101 01110001 11001001 10001100 10001000 01001011

I create an empty array:

random_byte_array = []

Then I appended each element into the empty array:

for bits in range(len(random_16_bytes)):
    random_byte_array.append(random_16_bytes[bits])
print(random_byte_array)

However the result is not as I wanted:

['1', '0', '0', '0', '1', '1', '0', '0', ' ', '1', '1', '0', '0', '1', '0', '1', '0', ' ', '1', '1', '1', '1', '1', '1', '0', '1', ' ', '1', '1', '0', '1', '0', '1', '0', '0', ' ', '0', '1', '1', '0', '1', '0', '1', '0', ' ', '0', '1', '0', '1', '1', '0', '0', '1', ' ', '0', '0', '0', '1', '0', '0', '0', '0', ' ', '1', '0', '1', '1', '1', '1', '1', '0', ' ', '0', '1', '1', '1', '1', '0', '0', '0', ' ', '1', '1', '1', '1', '1', '0', '1', '0', ' ', '0', '0', '1', '0', '0', '1', '0', '1', ' ', '0', '1', '1', '1', '0', '0', '0', '1', ' ', '1', '1', '0', '0', '1', '0', '0', '1', ' ', '1', '0', '0', '0', '1', '1', '0', '0', ' ', '1', '0', '0', '0', '1', '0', '0', '0', ' ', '0', '1', '0', '0', '1', '0', '1', '1', ' ']

CodePudding user response:

Without having a better look at your code and how your data is being generated I believe the option you really want is extend

random_byte_array = [] 
random_byte_array.extend(['10001100'])

This would need to be altered in a way that meets your specific needs, but this would create a blank array and allows you to add an entire binary to the end of the array. If you provide a little more detail on your code then we could probably get a little closer to what you are looking for.

CodePudding user response:

You can convert the bytes to string using str(random_byte_request). This will add b' at the start and ' at the end. So stripping that using [2:-1]. Split the string with space using .split(' '). If you want string in the list you can just keep x else if you want bytes in the list as well, encode the string using x.encode('utf8')

random_byte_request = b'10001100 11001010 11111101 11010100 01101010 01011001 00010000 10111110 01111000 11111010 00100101 01110001 11001001 10001100 10001000 01001011'
random_byte_array = [x.encode('utf8') for x in str(random_byte_request)[2:-1].split(' ')]
print(random_byte_array)
  • Related