int.to_bytes() 整数からバイト列への変換
最終更新:2026-09-22
int.to_bytes() 整数からバイト列への変換
int.to_bytes(length, byteorder) は整数を指定した長さのバイト列に変換する;byteorder は 'big' または 'little' を取る。
| カテゴリ | 数値型メソッド |
|---|---|
| 種類 | 組み込み型メソッド |
| Python バージョン | all |
📝 構文
int.to_bytes()
⚙️ 引数
| length 必須 | The length of the resulting bytes object. |
|---|---|
| byteorder 必須 | Byte order: 'big' for most-significant first, 'little' for least-significant first. |
| signed 任意 | Whether to use two's complement for signed integers.(デフォルト値:False) |
戻り値:bytes. The integer converted to bytes with the given length and byte order.
元のオブジェクトを変更するか:いいえ(新しいオブジェクトを返す)
💥 例外
OverflowError— Raised when the integer does not fit in length bytes.ValueError— Raised when byteorder is invalid, or signed is True and the integer is negative.
▶ 例
下のコードを編集し「実行」をクリックすると、出力パネルに結果が表示されます:
実行結果:
b'\x00\xff'
b'\xff\x00'
💡 関連するケース
さらに多くのケースは近日公開予定です。
❓ よくある質問
Qto_bytes() にはどのようなパラメータがありますか?
Alength(バイト数)と byteorder('big' は最上位バイトを先頭 / 'little' は最下位バイトを先頭)の両方が必須です。signed は任意で既定は False です。
Qlength が足りない場合はどうなりますか?
AOverflowError: int too big to convert が発生します。
Q負数を変換できますか?
A既定ではできません(OverflowError が発生)。signed=True にすると 2 の補数で変換します:(-1).to_bytes(2, 'big', signed=True) は b'\xff\xff' になります。
Qbyteorder の綴りを間違えるとどうなりますか?
AValueError が発生します。受け付けられるのは 'big' と 'little' だけです。