Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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') :
This fixes the issue:

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading