【发布时间】:2015-06-11 23:38:29
【问题描述】:
我正在使用串行接口与一台测试设备通话。设备的两个字母 ascii ID 在特定寄存器中编码为基数为 10 的整数。每对整数都需要转换为一个 ascii 字符。我的问题是进行这种转换的最佳方法是什么。我使用了下面的方法,但对于一个如此简单的任务来说,它似乎相当复杂。
例子
输入:5270
所需输出:'4F'(ascii 值为 52 和 70)
get the raw register value
>>> result =f4.read_register(0,)
>>> result
5270
convert the integer into a list of chars
>>> chars = [i for i in str(result)]
join the pairs together
>>> pairs = [''.join((chars[x], chars[x+1])) for x in xrange(0,len(chars),2)]
>>> pairs
['52', '70']
>>> pairs = [chr(int(x)) for x in pairs]
>>> pairs
['4', 'F']
【问题讨论】:
标签: python python-2.7 ascii