cla*_*ark 12 python 64-bit long-integer
我想将值表示为64位有符号long,这样大于(2**63)-1的值表示为负数,但Python long具有无限精度.对我来说,实现这一目标有"快捷"的方式吗?
Ste*_*202 13
你可以使用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
Run Code Online (Sandbox Code Playgroud)
如果您确定目标计算机上的64位宽,那么这只是一个选项signed long long.
编辑: jorendorff为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))
...
Run Code Online (Sandbox Code Playgroud)
通过这种方式ll(2 ** 63) - 1确实会产生结果9223372036854775807.这种结构可能会导致性能下降,因此根据您想要做的事情,定义上述类可能不值得.如有疑问,请使用timeit.
AFo*_*lia 11
你能用numpy吗?它有一个int64类型,完全符合你的要求.
In [1]: import numpy
In [2]: numpy.int64(2**63-1)
Out[2]: 9223372036854775807
In [3]: numpy.int64(2**63-1)+1
Out[3]: -9223372036854775808
Run Code Online (Sandbox Code Playgroud)
与ctypes示例不同,它对用户是透明的,并且它用C编码,因此它比在Python中滚动自己的类更快.Numpy可能比其他解决方案更大,但如果你正在进行数值分析,你会很感激.
| 归档时间: |
|
| 查看次数: |
31011 次 |
| 最近记录: |