Convert decimal string representation of an int to "bytes"

Question:

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').

Asked By: user3456269

||

Answers:

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

>>> x = 123456
>>> bs = str(x).encode('ascii')
>>> bs
b'123456'
Answered By: juanpa.arrivillaga

Think about what 10, 20 and 30 actually are. Sure, they are numbers, but exactly that 10 is just a decimal representation of the actual number. Usually, there are many different representation of a single number. For example 0xA, 0o12 and 0b1010 are different representations of the same number that is written as 10 in its decimal representation.

So first, you should think about how to get that decimal representation of a number. Luckily, that’s very easy since the decimal representation is the general default for numbers. So you just have to convert your number into a string by calling the str() function:

>>> str(10)
'10'
>>> str(20)
'20'

Once you do that, you have a string with the correct representation of your number. So all that’s left is asking how to convert that string into a bytes object. In Python 3, a bytes object is just a sequence of bytes. So in order to convert a string into a byte sequence, you have to decide how to represent each character in your string. This process is called encoding, and is done using str.encode(). For characters from the ASCII range, the actual encoding does not really matter as it is the same in all common encodings, so you can just stick with the default UTF-8:

>>> '10'.encode()
b'10'
>>> '20'.encode()
b'20'

So now you have everything you need. Just combine these two things, and you can convert your numbers into a bytes object of its decimal representation:

>>> str(10).encode()
b'10'
>>> str(20).encode()
b'20'
Answered By: poke
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.