Python Glossary Русский

Python 3.2+Numbers & mathfunction

int.to_bytes

bytes

Serialize the integer to a bytes object of the given length and byte order.

Syntax

n.to_bytes(length=1, byteorder='big', *, signed=False)

Sizing is on you: a value that does not fit in length bytes raises OverflowError instead of being truncated, and the minimum needed is (n.bit_length() + 7) // 8. Negative numbers require signed=True, otherwise you get the same OverflowError about converting a negative int to unsigned. The defaults length=1 and byteorder='big' only appeared in Python 3.11; before that both arguments were mandatory.

Examples

print((7).to_bytes(2, 'big'))       # → b'\x00\x07'
print((255).to_bytes(1, 'little'))  # → b'\xff'
print((1).to_bytes(2, 'little'))    # → b'\x01\x00'

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy