如何在Python中从整数创建字节值? [英] How can I create byte values from integers in Python?

查看:119
本文介绍了如何在Python中从整数创建字节值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:我需要将数字值作为字节发送到外部设备,但是遇到了问题. 我的代码是:

Background: I need to send a numerical value as a byte to an external device, but I have run into a problem. My code is:

ser=serial.Serial("COM3",9600, timeout=0)
ser.write(value)

其中值"是我读过的int.问题是,当我发送此消息时,它发送的是字符值,而不是实际值(我相信它会发送数字5的字节值31,因为我相信这是它的unicode位置)

where "value" is an int that I read have read. The problem is, when I send this, it sends the character value, not the actual value (it sends the byte value 31 for the number 5, since that is the unicode position for it, I believe)

实际上,我希望能够向其发送字符"\ x05".我想我的问题是,如何将int 5转换为char"\ x05"或将37转换为"\ x37"

In reality, I want to be able to send it the character "\x05" for example. I guess my question is, how would I convert and int 5 to a char "\x05", or 37 to "\x37"

推荐答案

使用内置函数

Use the built-in function chr().

如果您有需要发送的此类整数列表,则可以考虑使用 bytearray() .

If you have a list of such integers you need to send, you might consider using a bytearray().

或者,在新版本的Python中,您可以简单地使用byte类型.

Alternatively, in newer versions of Python you can simply use a byte type.

这篇关于如何在Python中从整数创建字节值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆