Skip to content Skip to sidebar Skip to footer

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 ju

Solution 1:

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

>>>x = 123456>>>bs = str(x).encode('ascii')>>>bs
b'123456'

Solution 2:

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'

Post a Comment for "Convert Int To "byte" In Python"