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?
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 ”.
We can use left shift operator to apply the check.
def check_32_bit(n):
return n<1<<31
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With