Python 类型 long 与 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
ctypes.c_longlong
:如果您确定
signed long long
在目标机器上的宽度为 64 位,那么这实际上仅是一个选项。编辑:jorendorff的想法 为 64 位数字定义一个类很有吸引力。理想情况下,您希望最大程度地减少显式类创建的数量。
使用
c_longlong
,你可以做这样的事情(注意:仅限Python 3.x!):这样的结果是
ll(2 ** 63) - 1
确实是9223372036854775807
。不过,这种构造可能会导致性能下降,因此根据您想要做什么,定义一个像上面这样的类可能不值得。如有疑问,请使用timeit
。You could use
ctypes.c_longlong
: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!):In this way the result of
ll(2 ** 63) - 1
will indeed be9223372036854775807
. 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, usetimeit
.你可以使用 numpy 吗?它有一个 int64 类型,可以完全满足您的需求。
与 ctypes 示例不同,它对用户是透明的,并且它是用 C 编写的,因此比在 Python 中滚动您自己的类更快。 Numpy 可能比其他解决方案更大,但如果您正在进行数值分析,您会很高兴拥有它。
Can you use numpy? It has an int64 type that does exactly what you want.
It's transparent to users, unlike the ctypes example, and it's coded in C so it'll be faster than rolling your own class in Python. Numpy may be bigger than the other solutions, but if you're doing numerical analysis, you will appreciate having it.
最快的事情可能是自己将结果截断为 64 位:
您当然可以定义自己的数字类型,每次执行任何类型的算术运算时都会自动执行此操作:
但这并不是特别“快”实现。
The quickest thing is probably to truncate the result to 64 bits yourself:
You can of course define your own numeric type that automatically does this every time you do any sort of arithmetic operation:
but that is not particularly "quick" to implement.
看一下 ctypes 模块,它用于从 python 调用外部 DLL/库。
有一些数据类型对应于C类型,例如
Have a look at the ctypes module, it is used to call foreign DLLs/libraries from python.
There a some data types that correspond to C types, for example