我正在使用串行接口(interface)与一台测试设备通话。设备的两个字母 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']
最佳答案
除了@BhargavRao 的回答,您还可以使用 divmod
内置:
num = 5270
''.join(map(chr, divmod(num, 100)))
# '4F'
您还可以使用字符串格式:
'{:c}{:c}'.format(*divmod(num, 100))
# '4F'
关于python - 在 python 中将 base 10 整数对转换为 ascii 字符的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30793198/