Integer Methods

int.to_bytes()

Encode an integer into exactly length bytes. The default is one byte, big-endian, unsigned. Signed encoding uses two’s complement; for positive lengths the signed range is -2**(8*length-1) through 2**(8*length-1)-1. Unsigned encoding requires a nonnegative integer less than 2**(8*length). Overflow raises OverflowError; negative length or unsupported byte order raises ValueError. Choose enough bytes before converting. Zero-length encoding has edge cases: CPython 3.13.5 accepts 0 and signed -1 as empty bytes; the latter does not round-trip. Prefer positive lengths for signed values.

Formal Syntax & Structure

python syntaxpython
value.to_bytes(length=1, byteorder='big', *, signed=False)

Parameters & Attributes

NameTypeDescription
lengthintExact number of output bytes; defaults to 1.
byteorderstrbig puts the most significant byte first; little puts it last.
signedboolUse signed two’s-complement interpretation when true; keyword-only.

Return Value

bytes

Immutable binary representation of requested length.

Working Example

Example Snippetpython
value = 258print(value.to_bytes(2, "big").hex())print(value.to_bytes(2, "little").hex())print((-2).to_bytes(2, signed=True).hex())
Python Reference