Python 类型 long 与 C 'long long'

标签 python 64-bit long-integer

我想将一个值表示为 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/

相关文章:

python - 为什么不能同时将 args 和仅关键字参数与 *args 和 **kwargs 混合

c# - 将 XNA 编译为 64 位

c++ - FindNextFile 在 64 位 Windows 上失败?

java - 从 double 到 long 的强制转换的细节

java - 使用数组和长数据类型会导致精度损失

输入字符串 ""的 java.lang.NumberFormatException

python - 打开 CV RTSP 相机缓冲区滞后

python - 带有 __set__ 但没有 __get__ 的描述符如何工作?

python - 使用 S3 网站源的 Cloudfront 对流层模板

c# - 从 x64 C# 应用程序调用 x86 PowerShell 脚本