Nasty_gri
Nasty_gri

Reputation: 103

Convert python list to bytearray and back

I have a list: ['qwe', 600, 0.1].

The goal is to convert the whole list to bytearray. I need to save types of items in list after decoding.

I have tried like this:

list = ['qwe', 600, 0.1]
new_list = []
for i in list:
   list_1 += [str(i)]
bytes = bytearray(','.join(new_list).encode('utf-8'))

#decoding is ugly:
item_list = [b.decode('utf-8') for b in bytes]
new_item_list = []
   for item in item_list:
      try:
         new_item_list += [int(item)]
      except ValueError:
         new_item_list += [item]
      final_list = []
      for item in new_item_list:
         if type(item) == int:
            final_list += [item]
         else:
            try:
               final_list += [float(item)]
            except ValueError:
               final_list += [item]

The disadvantage of this method is

1)Converting data to str loosing original types of items

2)first item in list can be for example '123' or 'qwe,rty' - that leads to a bug while decoding

I have also thought of this logic:

list = ['qwe', 600, 0.1]    
list_bytes=[]
for i in list:
   if type(i) == str:
      list_bytes += [bytearray(i.encode('utf-8'))]
   if type(i) == int or float:
      list_bytes += [i.to_bytes(2,byteorder='big')]
bytes = ','.join(list_bytes)

but I was stacked with decoding, don't know how to test whether an encoded item in list_bytes is str, int or float.

Upvotes: 0

Views: 1394

Answers (1)

hurlenko
hurlenko

Reputation: 1425

You can use pickle:

import pickle

data = ['qwe', 600, 0.1]

x = bytearray(pickle.dumps(data))
# x = bytearray(b'\x80\x04\x95\x17\x00\x00\x00\x00\x00\...')
y = pickle.loads(x)
# y = ['qwe', 600, 0.1]

Upvotes: 1

Related Questions