繁体   English   中英

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数据和转义十六进制字符串。 但是,是否应该有更直接的方式来进行这些操作? 我尝试使用解压缩,但是我遇到了错误。

干杯。

尝试使用struct module进行解包:

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格式使用大端字节顺序为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

PS可能需要其他字节序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM