Why am I getting an overflowerror in Python?
import random, codecs J = random.randrange(400000000000000000, 800000000000000000) K = codecs.encode(J.to_bytes(2, 'big'), "base64") # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # OverflowError: int too big to convert
The problem is that you don’t give him enough bytes in J.to_bytes(2, ‘big’). If you check the table below, you’ll see that to represent numbers as big, you need 8 bytes to store them.To fix the problem, you need to replace 2 bytes by 8 in the to_bytes function:
Here is an array of possibilities per size in byte (2^bits).
Please note that if the byte representation is signed, the maximum number is divided by 2, as 1 bit is used for the sign (+/-). So if the number you want to store is 200 as a signed int, then 2 bytes will be needed (-128 to +127) instead of one byte if it’s an unsigned int (0 to 255).Why am I getting an overflowerror in Python?