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

8

16

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?

Inspiratory answered 13/8, 2012 at 5:37 Comment(3)
lol...yes it does...but is it a valid way or are there better ways of doing so ?Inspiratory
Can you post your exact code, so we can see the implementation?Preceptor
I would probably use bitwise operators instead.Appreciate
F
9

Found answer here: https://docs.python.org/2/library/stdtypes.html#int.bit_length

Simplest and most effective solution I think

>>> your_num = 2147483651
>>> your_num.bit_length()
32
Federalism answered 7/12, 2022 at 10:18 Comment(1)
This function ignores the signed, a bit of checking must be addedBenoit
I
4

Just another idea, see if the value can be packed in a 4 bytes:

>>> from struct import pack, error
>>> def test_32bit(n):
...     try:
...             pack("i", n)
...     except error:
...             return False
...     return True
... 

If working with unsigned values, pack("I", n) instead.

Intercession answered 13/8, 2012 at 6:44 Comment(2)
Don't use a bare except clause, as it can catch things such as KeyboardInterrupt that should not be caught here.Rondarondeau
@AbeKarplus I know, but I was just being lazy :)Intercession
S
4

Assuming the largest 32-bit integer is 0xffffffff,

Then, we need to check if our number is larger than this value:

abs(n) <= 0xffffffff

Wrapping an abs() around the number will take care of negative cases, too.

Scott answered 1/3, 2018 at 11:46 Comment(2)
The positive and negative limits are not the same, -2^31 and 2^31-1Sontag
The hex value for a signed integer would be 0x7FFFFFFFLamebrain
F
3

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
Fleischer answered 13/8, 2012 at 6:4 Comment(7)
why can't I just check if it falls within the range of upper and lowerbound values ?Inspiratory
By using try with bin you are validating that n is a valid number. While you are at it, just check if the bits are less than 32 bits long. Works all day long...Fleischer
that's pretty cool..but isn't isDigit already checking if it is a valid number?Inspiratory
i am using the str.isDigit() method as a prescreen to check if it is a number representation at all, then typecasting it into it's integer representation and checking it against it's bounds !!!Inspiratory
@user1020069: That will probably work too. The way I have written it, Python is doing the math for you. If you are checking a string, it will choke on the valid number of is32(2**31) since the string contains '**' It is just more steps. Use what is appropriate for the context.Fleischer
@user1020069: You are maybe confusing a string number versus an int as well. Python is typed. '123' is not the same as 123Fleischer
does it lose it's precision ?Inspiratory
S
3
>>> def is_int32(number):
...     try:
...         return not(int(number)>>32)
...     except ValueError:
...         return False
Sebaceous answered 13/8, 2012 at 6:18 Comment(1)
This doesn't work for negative numbers: >>> is_int32(-1): FalseMelodiemelodion
S
3

We can use left shift operator to apply the check.

def check_32_bit(n):
    return n<1<<31
Snakebite answered 24/10, 2021 at 10:18 Comment(2)
Nice answer. Potentially more understandable variant: n<2**31Laura
Some explanation for this answer would be really helpful!Nombril
A
2

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

Architectonic answered 17/9, 2020 at 18:50 Comment(0)
E
0
>>> 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
Exostosis answered 6/7, 2021 at 12:15 Comment(1)
This is wrong. Check your ranges. 2**32 should be (2**31)-1.Humpy

© 2022 - 2024 — McMap. All rights reserved.