Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking type of big integer values without sign

Tags:

python

There is this code:

print isinstance(2147483647, int) # True - max signed 32-bit integer
print isinstance(4294967295, int) # False - max unsigned 32-bit integer
print isinstance(18446744073709551615, int) # False - max unsigned 64-bit integer

How to check if value is unsigned 32-bit integer and unsigned 64-bit integer?

like image 648
scdmb Avatar asked Mar 07 '26 23:03

scdmb


2 Answers

If you just intended to check whether the number fits in a 32 bit integer or 64 bit integer, there is a method called bit-length which you can check and determine if the result is less than 32 or not.

For ex.

>>> def Is32or64(x):
    return 32 if x.bit_length() < 32 else 64

>>> Is32or64(2**30)
32
>>> Is32or64(2**40)
64 
like image 195
Abhijit Avatar answered Mar 10 '26 13:03

Abhijit


You can not check for unsigned integer types because there are no unsigned integer types.

Python 2 has two types for integers: int (fixed range, platform dependent, 32-bit at least) and long (infinitely big integer). Both are signed.

In your example, the first value has type int and the other two are long. If you want to know if a value fits into range of 64-bit integer, do an ordinary comparison:

if (x >= 0) and (x < 2**64):
    pass

Starting with Python versions 2.7 and 3.1, there is int.bit_length() method which calculates how many bits a binary representation of the number has, ignoring the sign.

like image 30
hamstergene Avatar answered Mar 10 '26 13:03

hamstergene