Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert decimal string representation of an int to "bytes"

I need to convert an int, such as 123456, to bytes 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 b'10').

like image 568
user3456269 Avatar asked Nov 02 '25 08:11

user3456269


1 Answers

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

>>> x = 123456
>>> bs = str(x).encode('ascii')
>>> bs
b'123456'
like image 51
juanpa.arrivillaga Avatar answered Nov 03 '25 23:11

juanpa.arrivillaga