【问题标题】:Why does the maximium size of containers have a sign bit?为什么容器的最大尺寸有符号位?
【发布时间】:2019-07-23 02:24:52
【问题描述】:

我在 Python 3.6 中查看了sys.maxsize 的帮助:

>>> help(sys)
[...]
maxsize -- the largest supported length of containers.

测试它:

In [10]: '{:,}'.format(sys.maxsize)
Out[10]: '9,223,372,036,854,775,807'

In [11]: math.log2(sys.maxsize)
Out[11]: 63.0

它是 63 位,表示一个前导符号位。但是,容器的长度不能为负数。

这是怎么回事?

【问题讨论】:

  • 我不认为这是重复的;建议的帖子只是说 that sys.maxsize 是最大容器大小,而不是 为什么 它是 63 位,而不是 64 位。

标签: python python-3.x containers size signed


【解决方案1】:

容器的最大尺寸在 Python 2.5 中从 231-1 增加到 263-1。 PEP 353: Using ssize_t as the index type,介绍了变化,says

为什么不 size_t

实现此功能的初始尝试尝试使用 size_t。它 很快发现这是行不通的:Python 使用负索引 在许多地方(表示从末尾开始计数)。即使在某些地方 其中 size_t 可以使用,太多的代码重新表述 必要的,例如在循环中:

for(index = length-1; index >= 0; index--)

如果 index 从 int 更改为 size_t,此循环将永远不会终止。

因此,限制源于决定使用 Python 特定的“索引”类型,为了便于处理负索引,将其定义为有符号 (ssize_t) 而不是无符号 (size_t) 很方便。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    相关资源
    最近更新 更多