我想将一个值表示为 64 位带符号的 long
,这样大于 (2**63)-1
的值将表示为负数,但是 Python long
具有无限精度。有没有一种“快速”的方法可以让我实现这一目标?
最佳答案
你可以使用 ctypes.c_longlong
:
>>> from ctypes import c_longlong as ll
>>> ll(2 ** 63 - 1)
c_longlong(9223372036854775807L)
>>> ll(2 ** 63)
c_longlong(-9223372036854775808L)
>>> ll(2 ** 63).value
-9223372036854775808L
如果您确定 signed long long
在目标机器上将是 64 位宽,这实际上只是一个选项。
编辑: jorendorff's idea为 64 位数字定义一个类的做法很有吸引力。理想情况下,您希望尽量减少显式类创建的数量。
使用 c_longlong
,你可以做这样的事情(注意:仅限 Python 3.x!):
from ctypes import c_longlong
class ll(int):
def __new__(cls, n):
return int.__new__(cls, c_longlong(n).value)
def __add__(self, other):
return ll(super().__add__(other))
def __radd__(self, other):
return ll(other.__add__(self))
def __sub__(self, other):
return ll(super().__sub__(other))
def __rsub__(self, other):
return ll(other.__sub__(self))
...
这样,ll(2 ** 63) - 1
的结果确实是 9223372036854775807
。不过,这种构造可能会导致性能下降,因此根据您想要执行的操作,定义一个如上所示的类可能不值得。如有疑问,请使用 timeit
.
关于Python 类型 long 与 C 'long long',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1764548/