Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to check if integer fits in 64 bits

What is the Pythonic way (without using any external libraries) to check if an integer is small enough to fit in a 64 bit signed quantity?

Sorry if this question has been asked before!

like image 933
Curious Avatar asked Jul 13 '16 18:07

Curious


1 Answers

Just check the size with the int.bit_length() method:

if integer_value.bit_length() <= 63:

The method takes the absolute value, so you want to leave a bit for the sign:

>>> (-2 ** 63).bit_length()
64
>>> (2 ** 63).bit_length()
64
like image 71
Martijn Pieters Avatar answered Oct 06 '22 01:10

Martijn Pieters