Why am I getting an overflowerror in Python?

here's my code

J = random.randrange(400000000000000000, 800000000000000000)
K = codecs.encode(J.to_bytes(2, 'big'), "base64")

but i'm getting an overflow error when trying to run this... Basically I'm generating a number between 400000000000000000 and 800000000000000000 and converting it to base64. If anyone could help, that'd be great, thanks


As you said, the problem is an overflow :

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:

J.to_bytes(8, 'big')

Here is an array of possibilities per size in byte (2^bits).

Bytes Possibilities
1 256
2 65 536
4 4 294 967 296
7 72 057 594 037 927 900
8 18 446 744 073 709 600 000
Wanted: 800 000 000 000 000 000

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).