views:

38

answers:

2

Hi all, i am quite new in python.

I am receiving (through pyserial) string with data values. How can I parse these data to particular data structure?

I know that

 0-1 byte : id
 2-5 byte : time1 =>but little endian (lsb first)
 6-9 byte : time2 =>but little endian (lsb first)

and I looking for a function:

def parse_data(string):
  data={}
  data['id'] = ??
  data['time1'] = ??
  data['time2'] = ??
  return data

thanks

+2  A: 

The struct module should be exactly what you're looking for.

import struct
# ...
data['id'], data['time1'], data['time2'] = struct.unpack("<HII", string)

In the format string, < means "interpret everything as little endian, and don't use native alignment", H means "unsigned short" and I means "unsigned int"

Matti Virkkunen
additional question, what if I have in string: id(2bytes), time1(4bytes), somedata(0-10byte), time2(4bytes).. how can I define unpack()?
Meloun
@Meloun: That would depend on how the length of somedata is defined. If it depends on the other bytes in the message, you'll probably have to parse it piece-by-piece since I don't think struct has any mechanism for handling arbitrary variable-length data.
Matti Virkkunen
+2  A: 
import struct
def parse_data(string):
    return dict(zip(['id','time','time2'],struct.unpack("<HII", string)))
gnibbler