receive string with chars
i am quite new in python.
I am receiving (through pyserial) string with data values. How can 开发者_如何学PythonI 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
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"
import struct
def parse_data(string):
return dict(zip(['id','time','time2'],struct.unpack("<HII", string)))
精彩评论