Python - 将字符串和转义的十六进制字符串数据转换为整数的更好方法?

Python - Better way to convert string and escaped hex string data to integers?

我正在做一个项目,从 XBEE 无线电接收数据。数据以不同的字符串出现...我终于找到了一种提取实际信息的方法,但是,我真的认为必须有更好的方法将数据转换为可用形式。

这是一个框架的例子:

 {'analog_ch_mask': '\x18', 'first_sample': '\x03Q', 'number_samples': '\x01', 
 'options': '\xc1', 'addr_short': '\xff\xfe', 
 'address_low': '@c{!', 'digital_ch_mask': '\x00\x00', 
 'address_high':  '\x00\x13\xa2\x00', 'second_sample': '\x00\xca', 'id': 'io_sample_rx'}

我遇到的问题是数据的格式问题,以下是对我有用的。

# Extract the characters and join them together.
sample_data = ''.join("{:02X}".format(ord(c)) for c in item['key'])
print(sample_data)
print type(sample_data) # is a string
# Convert the hex string into an integer
sample_data = int(sample_data, 16)
print(sample_data)
print type(sample_data) # is an integer
# Try converting to hex string just for fun
sample_data = hex(sample_data)
print(sample_data)
print type(sample_data) # is a string

我喜欢这对 ascii 数据和转义十六进制字符串都有效。但是,难道不应该有更直接的方法来进行这些操作吗?我尝试使用 unpack,但出现错误。

干杯。

尝试使用struct模块解包:

import struct


frame = {'analog_ch_mask': '\x18', 'first_sample': '\x03Q', 'number_samples': '\x01', 
'options': '\xc1', 'addr_short': '\xff\xfe', 
'address_low': '@c{!', 'digital_ch_mask': '\x00\x00', 
'address_high':  '\x00\x13\xa2\x00', 'second_sample': '\x00\xca', 'id': 'io_sample_rx'}

print 'analog_ch_mask: %s' % struct.unpack('>B', frame['analog_ch_mask'])[0]
print 'first_sample: %s' % struct.unpack('>H', frame['first_sample'])[0]
print 'number_samples: %s' % struct.unpack('>B', frame['number_samples'])[0]
print 'options: %s' % struct.unpack('>B', frame['options'])[0]
print 'addr_short: %s' % struct.unpack('>H', frame['addr_short'])[0]
print 'address_low: %s' % struct.unpack('>I', frame['address_low'])[0]
print 'digital_ch_mask: %s' % struct.unpack('>H', frame['digital_ch_mask'])[0]
print 'address_high: %s' % struct.unpack('>I', frame['address_high'])[0]
print 'second_sample: %s' % struct.unpack('>H', frame['second_sample'])[0]
print 'id: %s' % frame['id']

这里>B>H>I格式的big-endian字节顺序分别为unsigned char (1 byte)unsigned short (2 bytes)unsigned int (4 bytes)用过的。

输出为:

analog_ch_mask: 24
first_sample: 849
number_samples: 1
options: 193
addr_short: 65534
address_low: 1080261409
digital_ch_mask: 0
address_high: 1286656
second_sample: 202
id: io_sample_rx

P.S。可能需要其他字节顺序。