Search code examples
pythonbyte

Num.to_bytes - OverflowError: int too big to convert


In order to convert -10947726235 into byte array I ran:

Num = -10947726235
ByteArray = Num.to_bytes(4, byteorder='little', signed=True)

I got:

OverflowError: int too big to convert

Can you please advise?


Solution

  • Four bytes can only represent a negative number of -2 billion-ish or lower.

    >>> int.from_bytes(bytes([0,0,0,0x80]), 'little', signed=True)
    -2147483648
    

    You need five bytes or more to represent your number:

    >>> Num = -10947726235
    >>> Num.to_bytes(5, 'little', signed=True).hex(' ')
    '65 f4 76 73 fd'