gpt4 book ai didi

bash - bash中定宽整数的宽度是多少?

转载 作者:行者123 更新时间:2023-11-29 09:28:03 25 4
gpt4 key购买 nike

Shell Arithmetic说:

Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error.

例子:

$ echo $(( 1 << 32 ))
4294967296
$ echo $(( (1 << 64) - 1 ))
0

bash 中 shell 算法的整数限制是什么?

@rici pointed outPOSIX shell保证 signed long 整数范围(由 ISO C 定义):

-2**31+1 to +2**31-1

@John Zwinck pointed outbash source code indicates that intmax_t is used :

All arithmetic is done as intmax_t integers with no checking for overflow

bash 是否保证在其文档中它使用 intmax_t 或其他一些 C 类型的整数?

最佳答案

Bash 没有记录整数的精确大小,并且大小可能因平台而异。

但是,它确实尝试符合 Posix,Posix 规定算术扩展使用有符号长算术,包括符号位在内至少为 32 位。

Posix 不要求整数算法对 k 的任何值取模 2k [但见注释 1],尽管 bash在通用平台上会这样做,并且它特别不能保证算术运算符的行为就像值是有符号长整型一样。 Posix 甚至允许使用 float 模拟整数运算,前提是浮点值具有足够的精度:

As an extension, the shell may recognize arithmetic expressions beyond those listed. The shell may use a signed integer type with a rank larger than the rank of signed long. The shell may use a real-floating type instead of signed long as long as it does not affect the results in cases where there is no overflow. (XSH §2.6.4)

这将允许在 long 的平台上使用 IEEE-754 浮点 double (53 位精度)例如,只有 32 位。同时 bash不这样做——如文档所述,bash使用固定宽度的整数数据类型——其他 shell 实现可能,并且可移植代码不应该做出假设。


注意事项:

  1. Posix 通常遵循 ISO C 标准,但 Posix 在许多地方添加了额外的约束,其中一些被标记为扩展 (CX):

    POSIX.1-2008 acts in part as a profile of the ISO C standard, and it may choose to further constrain behaviors allowed to vary by the ISO C standard. Such limitations and other compatible differences are not considered conflicts, even if a CX mark is missing. The markings are for information only.

    这些额外的约束之一是存在精确宽度的整数类型。标准 C 需要类型 int_{least,fast}{8,16,32,64}_t和他们未签名的类似物。它不需要精确宽度的类型,例如 int32_t ,除非某些整数类型符合条件。精确宽度类型必须具有与其名称中指示的位数完全相同的位数(即没有填充位)并且必须具有 2 的补码表示形式。所以INT32_MIN ,如果已定义,则必须正好是 -231 (§7.20.2.1)。

    但是,Posix 确实需要精确宽度的类型 int{8,16,32}_t (以及未签名的类似物),以及 int64_t如果实现提供了这样的类型。特别是,int64_t如果“实现支持 _POSIX_V7_LP64_OFF64 编程环境并且应用程序是在 _POSIX_V7_LP64_OFF64 编程环境中构建的”,则为必需。 (XBD, §13, stdint.h )(这些要求标记为 CX。)

    尽管 int32_t必须存在,因此必须有一些可用的 2 的补码类型,仍然不能保证 signed long是 2 的补码,即使是,也不能保证整数溢出回绕,而不是,例如,陷阱。

    不过,与原始问题最相关的事实是,即使 signed longint64_t 的类型相同即使有符号整数溢出回绕,shell 也没有任何义务实际使用 signed long用于算术扩展。它可以使用任何数据类型,“只要它在没有溢出的情况下不影响结果”。 (XSH,§2.6.4)

关于bash - bash中定宽整数的宽度是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26121659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com