Assuming you're on at least 3.2, there's a built in for this:

int.from_bytes( bytes, byteorder, *, signed=False )

...

The argument bytes must either be a bytes-like object or an iterable producing bytes.

The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.

The signed argument indicates whether two’s complement is used to represent the integer.

## Examples:
int.from_bytes(b'\x00\x01', "big")                         # 1
int.from_bytes(b'\x00\x01', "little")                      # 256

int.from_bytes(b'\x00\x10', byteorder='little')            # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)  #-1024
Answer from Peter DeGlopper on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-convert-bytes-to-int-in-python
How to Convert Bytes to Int in Python? - GeeksforGeeks
July 23, 2025 - The struct.unpack() function is part of Python's struct module. It unpacks a byte object into a tuple of values according to the format specified.
Discussions

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
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
Converting integer to byte string problem in python 3
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 ... More on discuss.python.org
🌐 discuss.python.org
6
0
August 27, 2020
Python 2,3 Convert Integer to "bytes" Cleanly - Stack Overflow
It converts the a number to bytes ... in a raw integer value, to the bytestring (e.g. (65).to_bytes()) is b'A', not b'65' as requested in the question). 2023-05-22T14:11:10.227Z+00:00 ... Save this answer. ... Show activity on this post. When converting from old code from python 2 you often ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-convert-bytes-to-int-in-python
How to Convert Bytes to Int in Python?
March 27, 2026 - The int.from_bytes() method is the most straightforward way to convert bytes to integers in Python. Remember to specify the correct byte order and use the signed parameter when dealing with signed integers.
🌐
Python
docs.python.org › 3 › builtins › stdtypes.html
Built-in Types — Python 3.14.7 documentation
If byteorder is "little", the most significant byte is at the end of the byte array. The signed argument determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
🌐
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?

🌐
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))
Find elsewhere
🌐
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...
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.

🌐
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 - 0...x...b...4. str(degree) will convert the number 180 into a string '180' containing the three characters '1', '8', '0'. Calling .encode() on that string will return a byte string version of the string b'180'. Python doesn't represent hexadecimal values in strings in the format 0xb4, it uses \xb4 To send an integer as a single byte if you know the range can only be from 0 to 180 (you can go up to 255),
🌐
GeeksforGeeks
geeksforgeeks.org › python › to-bytes-in-python
.to_bytes() in Python - GeeksforGeeks
December 18, 2025 - Return Type: Returns a bytes object representing the integer in the specified format. ... The byte 0x0A represents decimal 10. Python displays it as \n because that is its ASCII character, but it is still the numeric value 10. ... Converts -10 into a 2-byte big-endian bytes object using two’s complement.
🌐
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 - For such scenarios where your data in python script is in int or in long format, and underlying driver library used by python receives only bytes array. For such scenarios it is inevitable to convert int or long data to hex-decimal bytes array.
🌐
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('...
🌐
Arduino Forum
forum.arduino.cc › projects › interfacing w/ software on the computer
Converting from Int to byte to send over Serial to Raspberry Pi - Interfacing w/ Software on the Computer - Arduino Forum
July 6, 2018 - I've been looking through the forums and some lines of codes I've tried ended up not compiling or not working at all. I know there's a way to convert an int to a byte. I'm not entirely sure how to do it and I've tried using serial.write(variable, 2) to send something over but doesn't work.
🌐
YouTube
youtube.com › the python oracle
Convert bytes to int? - YouTube
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn--Music by Eric Matyashttps://www.soundimage.orgTrack title: Magic Oc
Published: April 5, 2023
Views: 55
🌐
Python
docs.python.org › 3 › builtins › exceptions.html
Built-in Exceptions — Python 3.14.7 documentation
In addition to those of OSError, BlockingIOError can have one more attribute: ... An integer containing the number of bytes written to the stream before it blocked.
🌐
W3Schools
w3schools.com › c › c_type_conversion.php
C Data Type Conversion
Convert a value from one C data type to another with implicit and explicit type conversion.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-string-to-bytes
Convert String to bytes-Python - GeeksforGeeks
The goal here is to convert a string into bytes in Python. This is essential for working with binary data or when encoding strings for storage or transmission.
Published: July 11, 2025
🌐
Python documentation
docs.python.org › 3 › library › sqlite3.html
sqlite3 — DB-API 2.0 interface for SQLite databases
Let’s go back to the Point class. We stored the x and y coordinates separated via semicolons as strings in SQLite. First, we’ll define a converter function that accepts the string as a parameter and constructs a Point object from it. ... Converter functions are always passed a bytes object, no matter the underlying SQLite data type.
🌐
Go
go.dev › doc › effective_go
Effective Go - The Go Programming Language
The method returns the number of bytes read and an error value, if any. To read into the first 32 bytes of a larger buffer buf, slice (here used as a verb) the buffer.