How do I check if a number is a 32-bit integer using Python?

Viewed 36462

In my program I'm looking at a string and I want to know if it represents a 32-bit integer.

Currently I first check if it is a digit at all using isdigit(), then I check if it exceeds the value of 2^32 (assuming I don't care about unsigned values).

What's the best way to check that my input string contains a valid 32-bit integer?

7 Answers

We can use left shift operator to apply the check.

def check_32_bit(n):
    return n<1<<31

The easy solution will be like this

if abs(number) < 2**31 and number != 2**31 - 1:
   return True
else:
   return False

If our number in [−2^31, 2^31 − 1] range we are good to go

>>> def is_32_bit(n: int) -> bool:
...     if n in range(-2 ** 31, (2**31) - 1):
...         return True
...     return False
... 
>>> is_32_bit(9999999999)
False
>>> is_32_bit(1)
True
Related