struct.pack is similar to PHPโ€™s pack. >>> from struct import pack >>> pack('b', 1) b'\x01' Beware that the format codes are different from PHP. >>> pack('4bi', 1, 2, 3, 4, 65535) b'\x01\x02\x03\x04\xff\xff\x00\x00' Answer from encukou on discuss.python.org
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ builtins โ€บ stdtypes.html
Built-in Types โ€” Python 3.14.7 documentation
An OverflowError is raised if the integer is not representable with the given number of bytes. The byteorder argument determines the byte order used to represent the integer, and defaults to "big". If byteorder is "big", the most significant byte is at the beginning of the byte array.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Converting integer to byte string problem in python 3 - Python Help - Discussions on Python.org
August 27, 2020 - I have a library function that is failing because I cannot seem to properly convert an integer to a proper byte string except by using a literal. Can someone explain why I get 3 different results from 3 different ways to convert an integer to a byte string? Using a literal, which is the only way the library call works produces this: >>> print(b'1') b'1' Using the builtin bytes function, which the library call rejects, is really strange: >>> i=1 >>> print(bytes(i)) b'\x00' Finally using the...
Discussions

Python 2,3 Convert Integer to "bytes" Cleanly - Stack Overflow
The problem is that google searching ... solving int to bytes, hence why I answered this question (I was trying to do what Tolli was doing). IMO These answers can easily co-exist here. Apparently all answers were downvoted which I think was unnecessary - they're all helpful. 2015-02-18T01:11:33.703Z+00:00 ... The .encode() call here is effectively a no-op in Python 2, since the ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - int to byte[] conversion, with 2 bytes?
Find answers to python - int to byte conversion, with 2 bytes? from the expert community at Experts Exchange More on experts-exchange.com
๐ŸŒ experts-exchange.com
September 28, 2014
Byte to integer ? why so complicated in python?
Hi, does anyone know how to read a byte from a binary file and convert to an integer I been busy for one hour on this, while it should be so simple, I keep running into errors after errors f = open(filename, "rb") a =โ€ฆ More on blenderartists.org
๐ŸŒ blenderartists.org
2
0
July 19, 2022
Convert a string byte to integer
The standard iterator for bytearray is of type int. ex: resp = bytearray(b'\xfa\xff\xff\xff\xff\xff\xff') for i in resp: print(i) results in... 250 255 255 255 255 255 255 More on reddit.com
๐ŸŒ r/learnpython
3
0
September 14, 2020
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-convert-int-to-bytes-in-python
How to Convert Int to Bytes in Python? - GeeksforGeeks
July 23, 2025 - For example, the integer 5 can be converted into bytes, resulting in a binary representation like b'\x00\x05' or b'\x05', depending on the chosen format. .to_bytes() method is the most direct way to convert an integer to bytes.
๐ŸŒ
Raspberry Pi Forums
forums.raspberrypi.com โ€บ board index โ€บ programming โ€บ python
how to convert an integer to byte(s) in python? - Raspberry Pi Forums
November 15, 2017 - In Python3 ints have a function to_bytes(length, byteorder, signed=False) that returns an array of bytes (a byte string) of a given length in the given byte order where 'big' means most significant byte first and 'little' means least significant byte first, and whether it is a signed integer ...
๐ŸŒ
Real Python
realpython.com โ€บ python-bytes
Bytes Objects: Handling Binary Data in Python โ€“ Real Python
March 5, 2025 - Browse Topics Guided Learning Paths Basics Intermediate Advanced ยท ai algorithms api best-practices career community databases data-science data-structures data-viz devops django docker editors flask front-end gamedev gui machine-learning news numpy projects python stdlib testing tools web-dev web-scraping ... The bytes data type is an immutable sequence of unsigned bytes used for handling binary data in Python.
Find elsewhere
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.

๐ŸŒ
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.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ bytes
Mimo: The coding platform you need to learn Web Development, Python, and more.
In Python 3, text is stored as str (Unicode) and binary data as bytes; this separation between data types helps prevent encoding bugs when mixing unicode and text encodings. ... A bytes object is defined by prefixing a string literal with a b. You can also use the bytes() constructor to create a bytes object from a string or an iterable of integers...
๐ŸŒ
Blender Artists
blenderartists.org โ€บ technical support โ€บ python support
Byte to integer ? why so complicated in python? - Python Support - Blender Artists Community
July 19, 2022 - Hi, does anyone know how to read a byte from a binary file and convert to an integer I been busy for one hour on this, while it should be so simple, I keep running into errors after errors f = open(filename, "rb") a = bytearray(b'\x00') a.append(f.read(1))
๐ŸŒ
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.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ how-to-convert-bytes-to-int-in-python
How to Convert Bytes to Int in Python?
March 27, 2026 - Converting bytes to integers is a common task when dealing with binary data, such as reading data from files or network sockets. By converting bytes to integers, we can perform various arithmetic and logical operations, interpret data, and manipulate it as needed.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ convert a string byte to integer
r/learnpython on Reddit: Convert a string byte to integer
September 14, 2020 -

Hi, I have a peculiar setup. I have a byte array converted to a string. It resembles something like: bytearray(b'\xfa\xff\xff\xff\xff\xff\xff....

The string arrives from a TCP socket, and I want to convert this string into a list or numpy array of integers from 0 to 255.

I am able to convert to a list resembling this: 'ff', 'ff', 'f9', 'ff', 'ff', 'ff', '00', '00', '00', '00', 'f6', 'ff', 'ff', 'ff', '00', '00', '00',...

However, using decode('utf-8') did not seem to work.

I have tried several methods with limited outcomes. For example, for loops and lambdas to iterate through each loop, trying to use int(), etc.

Since this is python 3, I get errors stating that 'Str' and list have no attribute 'decode.'

Any suggestions on making this more efficient? Some Codec function perhaps?

๐ŸŒ
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.
๐ŸŒ
Julia Programming Language
discourse.julialang.org โ€บ general usage
Converting string of bytes to integer - General Usage - Julia Programming Language
April 10, 2021 - I am working on interfacing Arduino with Julia. There is a particular experiment of reading the values from a sensor connected to Arduino. For this, I have written a function in Julia 1.6.0. This function reads the values coming from the serial port. These values are strings like @\x02.
๐ŸŒ
Quora
quora.com โ€บ How-do-you-convert-int-to-byte-in-Python
How to convert int to byte in Python - Quora
Answer: Do you want one byte or more than one - in theory a Python integer could be capable of being stored in one byte, or 4, or 20, or 400 โ€ฆ You can use the array [1]module. If you know that your integer fits into 4 bytes, you could do : [code]import array the_int = 56287 ar = array.array('...
๐ŸŒ
GitHub
gist.github.com โ€บ d81604135a1b94b773b6
How to convert bytes to integer in python ยท GitHub
How to convert bytes to integer in python. GitHub Gist: instantly share code, notes, and snippets.
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ sql โ€บ t-sql โ€บ functions โ€บ cast-and-convert-transact-sql
CAST and CONVERT (Transact-SQL) - SQL Server | Microsoft Learn
These functions convert an expression of one data type to another. ... Any valid expression. The target data type. This includes xml, bigint, and sql_variant. Alias data types can't be used. An optional integer that specifies the length of the target data type, for data types that allow a user specified length.
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Endianness
Endianness - Wikipedia
2 weeks ago - Of the two, big-endian is thus ... to bytes and assuming addresses increase from left to right. Both types of endianness are in widespread use in digital electronic engineering. The initial choice of endianness of a new design is often arbitrary, but later technology revisions and updates perpetuate the existing endianness to maintain backward compatibility. Big-endianness is the dominant ordering in networking protocols, such as in the Internet protocol suite, ...
๐ŸŒ
Raspberry Pi Forums
forums.raspberrypi.com โ€บ board index โ€บ hardware and peripherals โ€บ raspberry pi pico โ€บ micropython
Converting integer to bytes - Raspberry Pi Forums
Hello, new issue arrived in code transfer from python to micropython. Code below explains all I hope. I Couldnt find any example on the net, ... input is: 2289165400 output should be: [136, 113, 228, 88] Code: Select all ยท def convert_int_to_bytes(x): y = x.to_bytes(4,"big",signed=False) z = [int(i) for i in y] return z in = 2289165400 # -> [136, 113, 228, 88] out = convert_int_to_bytes(in) print(out) horuable ยท