user3456269 user3456269 - 3 years ago 287
Python Question

Convert int to "byte" in Python

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'

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

Any help or advice on forcing this translation is very much appreciated!!

Answer Source

Convert the int to a str then .encode into bytes:

>>> x = 123456
>>> bs = str(x).encode('ascii')
>>> bs
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download