You can use the struct module to convert between integers and representation as bytes. In your case, to convert from a Python integer to two bytes and back, you'd use:

>>> import struct
>>> struct.pack('>H', 12345)
'09'
>>> struct.unpack('>H', '09')
(12345,)

The first argument to struct.pack and struct.unpack represent how you want you data to be formatted. Here, I ask for it to be in big-ending mode by using the > prefix (you can use < for little-endian, or = for native) and then I say there is a single unsigned short (16-bits integer) represented by the H.

Other possibilities are b for a signed byte, B for an unsigned byte, h for a signed short (16-bits), i for a signed 32-bits integer, I for an unsigned 32-bits integer. You can get the complete list by looking at the documentation of the struct module.

Answer from Sylvain Defresne on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › 2 byte number through bytes()
r/learnpython on Reddit: 2 byte number through bytes()
December 21, 2021 -

Coming from a primarily C++ background.

Is there anyway to get around bytes() restriction of only allowing single byte data? I have a single, 2 byte number in my list of single byte numbers that I need serialized in order to send through serial.Serial.write(). I'm not sure how to approach this exactly given pythons inherency to obscure addresses and such unlike a language like C++/C.

And this is all assuming I'm interpreting the error messages properly. Thanks

Discussions

python - Convert int to 2 bytes of Big-Endian - Stack Overflow
I have a problem converting an int to 2 hex bytes of Big-Endian encoding. for example: import struct a = 1234 struct.pack('>I', a) what I receive is: '\x00\x00\x04\xd2' what I wish to receiv... More on stackoverflow.com
🌐 stackoverflow.com
Python 2,3 Convert Integer to "bytes" Cleanly - Stack Overflow
@Startec indeed there is a difference: ... . First is a class and later a primitive. Both are functional identical. However in some situations only one of these may be accepted. Not yet encountered that in python. But recently I had struggle in C# with int and Integer. Only the later you can use in generics. Functions demanding 'primitive' int won't accept Integer. Convert int into Integer is 'costly'. So these are like two paths you ... More on stackoverflow.com
🌐 stackoverflow.com
network programming - How to change one byte int to two bytes in Python? - Stack Overflow
Explore Stack Internal ... I am making a basic server/client program, and I am making the client in Python. I have to format the message before I send it. The first field is for message length. I can compute the message length, but I need to store the value in the first two bytes of my bytearray. More on stackoverflow.com
🌐 stackoverflow.com
May 23, 2017
Convert an integer to a 2 byte Hex value in Python - Stack Overflow
For a tkinter GUI, I must read in a Hex address in the form of '0x00' to set an I2C address. The way I am currently doing it is by reading the input as a string, converting the string to an integer... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Experts Exchange
experts-exchange.com › questions › 28526959 › python-int-to-byte-conversion-with-2-bytes.html
Solved: python - int to byte[] conversion, with 2 bytes? | Experts Exchange
September 28, 2014 - Hi I've queried parts of this issue before, but for 4 bytes to hold an integer value for a networking message byte[] encoding. - in Java I think a 2 byte, intToBytes and BytesToInt system would be better for an RTS. using 4 bytes might be risky with UDP data loss issues and unnecessary size needs.
🌐
w3resource
w3resource.com › python-exercises › math › python-math-exercise-80.php
Python Math: Convert an integer to a 2 byte Hex value - w3resource
Write a Python function that accepts an integer, converts it to a 2-byte hex value, and returns the formatted string.
🌐
Medium
medium.com › @dattatray.hinge › python-2-int-to-bytes-array-90dc115f6aaa
Python 2: int to bytes array. python 2: int to bytes array conversion | by Dattatray Hinge | Medium
September 17, 2019 - In python 3, where all numbers are int type irrespective of size of number and fortunately there is built in method i.e. int.to_bytes() to convert such numbers to bytes array.
Top answer
1 of 7
52

Answer 1:

To convert a string to a sequence of bytes in either Python 2 or Python 3, you use the string's encode method. If you don't supply an encoding parameter 'ascii' is used, which will always be good enough for numeric digits.

s = str(n).encode()
  • Python 2: http://ideone.com/Y05zVY
  • Python 3: http://ideone.com/XqFyOj

In Python 2 str(n) already produces bytes; the encode will do a double conversion as this string is implicitly converted to Unicode and back again to bytes. It's unnecessary work, but it's harmless and is completely compatible with Python 3.


Answer 2:

Above is the answer to the question that was actually asked, which was to produce a string of ASCII bytes in human-readable form. But since people keep coming here trying to get the answer to a different question, I'll answer that question too. If you want to convert 10 to b'10' use the answer above, but if you want to convert 10 to b'\x0a\x00\x00\x00' then keep reading.

The struct module was specifically provided for converting between various types and their binary representation as a sequence of bytes. The conversion from a type to bytes is done with struct.pack. There's a format parameter fmt that determines which conversion it should perform. For a 4-byte integer, that would be i for signed numbers or I for unsigned numbers. For more possibilities see the format character table, and see the byte order, size, and alignment table for options when the output is more than a single byte.

import struct
s = struct.pack('<i', 5) # b'\x05\x00\x00\x00'
2 of 7
38

You can use the struct's pack:

In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'

The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:

In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'

In [13]: struct.pack("B", 1)
Out[13]: '\x01'

This works the same on both python 2 and python 3.

Note: the inverse operation (bytes to int) can be done with unpack.

🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-convert-int-to-bytes-in-python
How to Convert Int to Bytes in Python? - GeeksforGeeks
July 23, 2025 - .to_bytes() method is the most direct way to convert an integer to bytes. It allows specifying the byte length and byte order (big for big-endian, little for little-endian). ... Explanation: Here, 2 ensures a fixed 2-byte representation, adding ...
Find elsewhere
🌐
Delft Stack
delftstack.com › home › howto › python › how to convert bytes to integers
How to Convert Bytes to Int in Python 2.7 and 3.x | Delft Stack
February 2, 2024 - HH means there are two objects of H types in the bytes string. H represents an unsigned short integer that takes 2 bytes.
🌐
Delft Stack
delftstack.com › home › howto › python › how to convert int to bytes in python 2 and python 3
How to Convert Int to Bytes in Python 2 and Python 3 | Delft Stack
February 2, 2024 - The integer must be surrounded by the parenthesis, otherwise, you will get the bytes object of size given by the parameter initialized with null bytes but not the corresponding bytes. ... From Python3.1, a new integer class method int.to_bytes() is introduced.
🌐
GeeksforGeeks
geeksforgeeks.org › python › to-bytes-in-python
.to_bytes() in Python - GeeksforGeeks
December 18, 2025 - Explanation: num.to_bytes(2, 'little') converts integer 10 into 2 bytes using little-endian order. Note: The byte 0x0A represents decimal 10. Python prints this byte as \n because it corresponds to the newline character.
🌐
Coderwall
coderwall.com › p › x6xtxq › convert-bytes-to-int-or-int-to-bytes-in-python
Convert bytes to int or int to bytes in python (Example)
September 29, 2021 - #python · def bytes_to_int(bytes): result = 0 for b in bytes: result = result * 256 + int(b) return result def int_to_bytes(value, length): result = [] for i in range(0, length): result.append(value >> (i * 8) & 0xff) result.reverse() return result · #python · Say Thanks ·
🌐
Tutorial Reference
tutorialreference.com › python › examples › faq › python-how-to-convert-int-to-bytes-and-viceversa
How to Convert Integers to Bytes in Python | Tutorial Reference
March 29, 2025 - It's important to distinguish between converting an integer directly to bytes (using to_bytes()) and converting an integer to its string representation and then encoding that string: ... num.to_bytes(2, 'big'): This gives the binary representation of the number 2048, which requires two bytes ...
🌐
Appdividend
appdividend.com › convert-int-to-bytes-and-bytes-to-int-in-python
How to Convert Int to Bytes and Bytes to Int in Python
September 14, 2025 - If you are working with negative numbers, set the signed parameter to True. main_int = -1028 converted_byte = (main_int).to_bytes(2, 'big', signed=True) print(converted_byte) # Output: b'\xfb\xfc'
🌐
Data Science Parichay
datascienceparichay.com › home › blog › convert int to bytes in python
Convert int to bytes in Python - Data Science Parichay
March 12, 2022 - Let’s use the same example as above but with “little” as the byteorder ... Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers. # integer variable num = 7 # integer to bytes num_bytes = num.to_bytes(2, byteorder='little') # display result and type print(num_bytes) print(type(num_bytes))
🌐
YouTube
youtube.com › watch
Convert Integer to Bytes in Python - YouTube
This video tutorial demonstrates how to convert integer to bytes in Python.Refer to this text version below.https://www.delftstack.com/howto/python/how-to-co...
Published: July 4, 2023
🌐
Reddit
reddit.com › r/learnprogramming › writing a short (two-byte integer) into a file with python
r/learnprogramming on Reddit: writing a short (two-byte integer) into a file with python
March 1, 2013 -

I want to write a number to a binary file in two bytes. Any tips on how to do this? I guess I can manually do some math to figure out what each byte of the short would be, but I'm wondering if there's a better way. I'm new to python.

Thanks all.

Top answer
1 of 2
1

You have to do similar to calculation on paper.

You have to loop and get modulo 256, and divide by 256, and repeat it on result.

def int_to_bytes(val):
    data = []
    while val > 0:
        b = val % 256
        val = val // 256
        data.insert(0, b)
    return bytes(data)

print( int_to_bytes(127) )        # b'\x7f'
print( int_to_bytes(3000) )       # b'\x0b\xb8'
print( int_to_bytes(985983) )     # b'\x0f\x0b\x7f'
print( int_to_bytes(184553088) )  # b'\x0b\x00\x0e\x80'

EDIT:

Similar code you can use to convert to other systems, 8, 2, etc.

Using 2 instead of 256 you can get bits

def int_to_bits(val):
    data = []
    while val > 0:
        b = val % 2
        val = val // 2
        char = chr(ord('0') + b)
        data.insert(0, char)
    return ''.join(data)

print( int_to_bits(127) )        # 1111111
print( int_to_bits(3000) )       # 101110111000
print( int_to_bits(985983) )     # 11110000101101111111
print( int_to_bits(184553088) )  # 1011000000000000111010000000

And exactly the same for 8

def int_to_octals(val):
    data = []
    while val > 0:
        b = val % 8
        val = val // 8
        char = chr(ord('0') + b)
        data.insert(0, char)
    return ''.join(data)

print( int_to_octals(127) )        # 177
print( int_to_octals(3000) )       # 5670
print( int_to_octals(985983) )     # 3605577
print( int_to_octals(184553088) )  # 1300007200

For values bigger than 10 it can be simpler to use list with digits

    digit = '0123456789ABCDEF'
    char = digit[b]
def int_to_hexs(val):
    digit = '0123456789ABCDEF'
    data = []
    while val > 0:
        b = val % 16
        val = val // 16
        char = digit[b]
        data.insert(0, char)
    return ''.join(data)

print( int_to_hexs(127) )        # 7F
print( int_to_hexs(3000) )       # BB8
print( int_to_hexs(985983) )     # F0B7F
print( int_to_hexs(184553088) )  # B000E80
2 of 2
1

As you mentioned above :

def int_to_2bytes(b):
    if b > 0 or b < 65335: # if b > 0 and b <= 65335: (corrected) 
        return bytes([b//256, b-(b//256*256)])

This can be rewritten as:

def int_to_2bytes(b):
    if b > 0 and b < 256**2:
        return bytes([(b//256**1)-(b//256**2*256),
                      (b//256**0)-(b//256**1*256)])

For int_to4bytes :

def int_to_4bytes(b):
    if b > 0 and b < 256**4:
        return bytes([(b//256**3)-(b//256**4*256),
                      (b//256**2)-(b//256**3*256),
                      (b//256**1)-(b//256**2*256),
                      (b//256**0)-(b//256**1*256)])

Following the same pattern, for int_to_nbytes :

def int_to_nbytes(b, n):
    if b > 0 and b < 256**n:
        return bytes([b//256**(n-1-i) - b//256**(n-i)*256 for i in range(n)])


print(int_to_nbytes(3000, 4)) # b'\x00\x00\x0b\xb8'
print(int_to_nbytes(3000, 8)) # b'\x00\x00\x00\x00\x00\x00\x0b\xb8'