int.to_bytes()
The serialization half of the pair with from_bytes. You choose the width and the byte order; Python refuses rather than truncate if the value will not fit.
Demo
to_bytes writes the value into exactly `length` bytes, padding the high side with zeros. Byte order decides which end the most significant byte goes: 255 in two bytes is b"\x00\xff" big-endian and b"\xff\x00" little-endian. Two things raise instead of guessing — a value wider than the requested length (OverflowError: int too big to convert) and a negative value without signed=True (OverflowError: can't convert negative int to unsigned).
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| length | int | no (1) | How many bytes to produce. Since 3.11 it defaults to 1. Too small for the value raises OverflowError. |
| byteorder | str | no ('big') | 'big' puts the most significant byte first; 'little' puts it last. Since 3.11 it defaults to 'big'. Anything else raises ValueError. |
| signed | bool | no (False) | Keyword-only. False rejects negative values; True encodes them in two-complement form. |
Return value
bytes — A bytes object of exactly `length` bytes. Raises OverflowError if the value does not fit.
Common patterns
header = length.to_bytes(4, 'big')
width = max(1, n.bit_length() + 7 >> 3) blob = n.to_bytes(width, 'big')
(-1).to_bytes(2, 'big', signed=True) # b'\xff\xff'
Examples
Pitfalls
(-1).to_bytes(2, 'big')
(-1).to_bytes(2, 'big', signed=True)
(256).to_bytes(1, 'big')
n.to_bytes(max(1, (n.bit_length() + 7) // 8), 'big')
(200).to_bytes(1, 'big', signed=True)
(200).to_bytes(1, 'big')
(255).to_bytes()
(255).to_bytes(1, 'big')
When to use
- Writing fixed-width integers into a binary protocol or file format
- Producing network byte order without pulling in struct
- Hashing or checksumming an integer as raw bytes
- Round-tripping with int.from_bytes
- Packing several fields at once → struct.pack is clearer
- Text output → format, hex or bin
- Arbitrary objects → pickle or a real serializer
Notes
FAQ
Big-endian for anything crossing a wire or a file format, because it is network byte order and most specifications assume it. Little-endian when matching x86 memory layout or a format that specifies it. If you control both ends, pick one and write it down.
n.to_bytes(4, 'big') # network order