PyDocs

Nav

Python Runtime Services

int.to_bytes

builtins

method of int · Added in 3.2
  • int.to_bytes(length=1, byteorder='big', *, signed=False)
Return an array of bytes representing an integer.

length
  Length of bytes object to use.  An OverflowError is raised if
  the integer is not representable with the given number of bytes.
  Default is length 1.
byteorder
  The byte order used to represent the integer.  If byteorder is
  'big', the most significant byte is at the beginning of the byte
  array.  If byteorder is 'little', the most significant byte is at
  the end of the byte array.  To request the native byte order of
  the host system, use sys.byteorder as the byte order value.
  Default is to use 'big'.
signed
  Determines whether two's complement is used to represent the
  integer.  If signed is False and a negative integer is given,
  an OverflowError is raised.
Changed in 3.11
  • 3.11: Added default argument values for length and byteorder.
1 Example
>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'\xe8\x03'
from the Python docs
See Also
No see-alsos for builtins/int.to_bytes
0 Notes
No notes for int.to_bytes