Python类型long vs C'long long' [英] Python type long vs C 'long long'

查看:408
本文介绍了Python类型long vs C'long long'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个值表示为一个64位带符号的long,以便将大于(2**63)-1的值表示为负数,但是Python long具有无限的精度.我有实现这个目标的快速"方法吗?

I would like to represent a value as a 64bit signed long, such that values larger than (2**63)-1 are represented as negative, however Python long has infinite precision. Is there a 'quick' way for me to achieve this?

推荐答案

您可以使用

You could use 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位,这实际上是一个选项.

This is really only an option if you know for sure that a signed long long will be 64 bits wide on the target machine(s).

编辑: jorendorff的想法为64位数字定义一个类很吸引人.理想情况下,您希望最大程度地减少显式类的创建.

jorendorff's idea of defining a class for 64 bit numbers is appealing. Ideally you want to minimize the number of explicit class creations.

使用c_longlong,您可以执行以下操作(注意:仅适用于Python 3.x!):

Using c_longlong, you could do something like this (note: Python 3.x only!):

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 .

In this way the result of ll(2 ** 63) - 1 will indeed be 9223372036854775807. This construction may result in a performance penalty though, so depending on what you want to do exactly, defining a class such as the above may not be worth it. When in doubt, use timeit.

这篇关于Python类型long vs C'long long'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆