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

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

问题描述

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

解决方案

您可以使用 ctypes.c_longlong:

<预><代码>>>>从 ctypes 导入 c_longlong as ll>>>ll(2 ** 63 - 1)c_longlong(9223372036854775807L)>>>ll(2 ** 63)c_longlong(-9223372036854775808L)>>>ll(2 ** 63).值-9223372036854775808L

如果您确定signed long long 在目标机器上将是 64 位宽,这实际上是唯一一个选项.

jorendorff 的想法 为 64 位数字定义一个类很有吸引力.理想情况下,您希望尽量减少显式创建类的数量.

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

from ctypes import c_longlong类 ll(int):def __new__(cls, n):返回 int.__new__(cls, c_longlong(n).value)def __add__(self, other):返回 ll(super().__add__(other))def __radd__(self, other):返回 ll(other.__add__(self))def __sub__(self, other):返回 ll(super().__sub__(other))def __rsub__(self, other):返回 ll(other.__sub__(self))...

这样ll(2 ** 63) - 1的结果确实是9223372036854775807.但是,这种构造可能会导致性能下降,因此根据您想要做什么,定义一个像上面这样的类可能不值得.如有疑问,请使用 timeit.>

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

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).

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

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))

    ...

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 与 C 'long long'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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