您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python类型long vs C'long long'

Python类型long vs C'long 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

如果您确实知道目标计算机上的a将是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))

    ...

这样,结果ll(2 ** 63) - 1的确是9223372036854775807。但是,这种构造可能会导致性能下降,因此根据您要精确执行的操作,定义上述类可能不值得。如有疑问,请使用timeit

python 2022/1/1 18:50:16 有365人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶