将整数转换为字节(用于PySerial,使用Python25)
这看起来应该很简单,但我一直没能搞明白...
我正在尝试使用 PySerial 来和一个微控制器进行通信。我想发送一个索引位置,但当我发送这个位置时,PySerial 发送的是这个数字的 ASCII 值(比如我发送 0,它发送的是 48)。
我知道在 Python 2.6 及以上版本中,我只需要用内置的 bytes 函数把数字包起来,就像这样:
self.index = bytes([index])
但是,Python 2.5 没有这个函数。我找不到任何文档说明有什么等效的办法。有没有人知道我该怎么做?
提前谢谢大家!
编辑:抱歉,这里是我代码的简化版本...
class SecondaryImage():
def __init__(self, index):
self.index = index
def sendIndex(self):
serial.write(self.index)
for i in range(64):
img = SecondaryImage(i)
imgs.append(img)
然后我会单独调用 sendIndex() --
imgs[2].sendIndex()
3 个回答
0
你试过使用binascii模块吗?
http://docs.python.org/release/2.5.4/lib/module-binascii.html
1
串口通信使用的是ASCII编码,所以你需要用chr
这个函数把数字转换成对应的ASCII字符。
2
chr
是一个内置函数,它可以根据你输入的数字返回对应的字符。