Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

int

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?

like image 657
user1020069 Avatar asked Aug 13 '12 05:08

user1020069


People also ask

How do you check in Python if a number is an integer?

To check if the variable is an integer in Python, we will use isinstance() which will return a boolean value whether a variable is of type integer or not. After writing the above code (python check if the variable is an integer), Ones you will print ” isinstance() “ then the output will appear as a “ True ”.


2 Answers

We can use left shift operator to apply the check.

def check_32_bit(n):
    return n<1<<31
like image 127
29-dk Avatar answered Oct 07 '22 12:10

29-dk


For unsigned values, this will work:

>>> def is32(n):
...     try:
...         bitstring=bin(n)
...     except (TypeError, ValueError):
...         return False
...         
...     if len(bin(n)[2:]) <=32:
...         return True
...     else:
...         return False    
... 
>>> is32(2**32)
False
>>> is32(2**32-1)
True
>>> is32('abc')
False
like image 32
dawg Avatar answered Oct 07 '22 10:10

dawg