将int转换为"byte"在Python中 [英] Convert int to "byte" in Python
问题描述
这是一个有点奇怪的问题.我需要将整数id(例如123456)转换为格式为b'123456'的字节.我没有真正转换为字节,但是,我只是将格式更改为看起来像一个字节并被解释为一个字节.因此,我确实需要执行以下操作:
This is a somewhat strange question. I need to convert an integer id, such as 123456, to a byte in the format b'123456'. I'm not doing an actual conversion to bytes however, I'm just changing the format to look like a byte and be interpreted as one. So I literally need to do the following:
10 = b'10'
20 = b'20'
30 = b'30'
等等.我无法转换为字符串,因为我需要结果以字节为单位,并且我无法进行实际的字节转换,因为 bytes([10])== b'\ n'
(而不是 b'10'
).
and so. I can't convert to a string because I need the results to be in bytes, and I can't do an actual byte conversion because bytes([10]) == b'\n'
(and not b'10'
).
非常感谢您提供有关强制翻译的帮助或建议!
Any help or advice on forcing this translation is very much appreciated!!
推荐答案
将 int
转换为 str
,然后将 .encode
转换为字节
:
Convert the int
to a str
then .encode
into bytes
:
>>> x = 123456
>>> bs = str(x).encode('ascii')
>>> bs
b'123456'
这篇关于将int转换为"byte"在Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!