int.to_bytes() Int to bytes

Last updated: 2026-09-22

int.to_bytes() Int to bytes

int.to_bytes(length, byteorder) converts an int to bytes; byteorder is 'big' or 'little'.

CategoryNumber Methods
KindBuilt-in Type Method
Python Versionall

📝 Syntax

int.to_bytes()

⚙️ Parameters

length RequiredThe length of the resulting bytes object.
byteorder RequiredByte order: 'big' for most-significant first, 'little' for least-significant first.
signed OptionalWhether to use two's complement for signed integers.(Default:False)

Returns:bytes. The integer converted to bytes with the given length and byte order.

Mutates the original:No (returns a new object)

💥 Raises

▶ Example

Edit the code, press Run, and see the result in the output panel:

Output:

b'\x00\xff'
b'\xff\x00'
More case studies coming soon — check back later.

❓ FAQ

QWhat parameters does to_bytes() have?
ABoth length (number of bytes) and byteorder ('big' for most significant first / 'little' for least significant first) are required; signed is optional and defaults to False.
QWhat happens when length is not enough?
AAn OverflowError: int too big to convert is raised.
QCan negative numbers be converted?
ANot by default (raises OverflowError); with signed=True it converts using two's complement: (-1).to_bytes(2, 'big', signed=True) gives b'\xff\xff'.
QWhat happens when byteorder is misspelled?
AA ValueError is raised; only 'big' and 'little' are accepted.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏