int.from_bytes()
The inverse of to_bytes, and a classmethod — you call it on the int type, not on a value. Any length of input is accepted, including empty.
Demo
from_bytes reads the bytes as digits of a base-256 number. Byte order decides which end is most significant, which is why b"\x00\xff" is 255 big-endian but 65280 little-endian. Unlike to_bytes there is no width to overflow — any number of bytes is valid, and empty input is defined as 0. Leading zero bytes simply do not contribute.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| bytes | bytes-like | yes | A bytes, bytearray, or any iterable of ints in range(256). Empty is allowed and yields 0. |
| byteorder | str | no ('big') | 'big' reads the most significant byte first; 'little' reads it last. Since 3.11 it defaults to 'big'. |
| signed | bool | no (False) | Keyword-only. True interprets the input as two-complement, so a high top bit means a negative result. |
Return value
int — The integer the bytes represent. Empty bytes give 0. Never raises for width — any length is valid.
Common patterns
length = int.from_bytes(header[:4], 'big')
value = int.from_bytes(hashlib.sha256(data).digest(), 'big')
raw = (-1).to_bytes(2, 'big', signed=True) int.from_bytes(raw, 'big', signed=True) # -1
Examples
Pitfalls
raw = (255).to_bytes(2, 'big') int.from_bytes(raw, 'little')
raw = (255).to_bytes(2, 'big') int.from_bytes(raw, 'big')
raw = (-1).to_bytes(2, 'big', signed=True) int.from_bytes(raw, 'big')
int.from_bytes(raw, 'big', signed=True)
(0).from_bytes(b'\x01', 'big')
int.from_bytes(b'\x01', 'big')
When to use
- Reading fixed-width integers out of a binary protocol or file
- Converting a digest or nonce into a number
- Round-tripping values written with to_bytes
- Decoding arbitrary-length big integers, which struct cannot do
- Unpacking several fields at once → struct.unpack
- Parsing text digits → int(s) or int(s, base)
- Untrusted length prefixes → validate before allocating on the result
Notes
FAQ
It falls out of reading the input as a base-256 number: an empty sequence of digits sums to nothing, so the value is 0. It also makes from_bytes total — no length is invalid — which is why only to_bytes can raise OverflowError.
int.from_bytes(b'', 'big') # 0