[英]How do I check if a number is a 32-bit integer using Python?
In my program I'm looking at a string and I want to know if it represents a 32-bit integer.在我的程序中,我正在查看一个字符串,我想知道它是否代表 32 位 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).目前我首先使用
isdigit()
检查它是否是一个数字,然后我检查它是否超过 2^32 的值(假设我不关心无符号值)。
What's the best way to check that my input string contains a valid 32-bit integer?检查我的输入字符串是否包含有效的 32 位 integer 的最佳方法是什么?
Assuming the largest 32-bit integer is 0xffffffff
,假设最大的 32 位整数是
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.在数字周围包裹一个
abs()
也将处理负面情况。
Just another idea, see if the value can be packed in a 4 bytes:只是另一个想法,看看值是否可以打包成 4 个字节:
>>> 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.如果使用无符号值,则改为
pack("I", n)
。
>>> def is_int32(number):
... try:
... return not(int(number)>>32)
... except ValueError:
... return False
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
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如果我们的数字在
[−2^31, 2^31 − 1]
范围内,我们很高兴
>>> 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
We can use left shift operator to apply the check.我们可以使用左移运算符来应用检查。
def check_32_bit(n):
return n<1<<31
Found answer here: https://docs.python.org/2/library/stdtypes.html#int.bit_length在这里找到答案: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.