bash - BASH 处理数字的能力是否与处理器位宽成正比?

标签 bash

我最近不得不为 BASH 编写一个库来处理大量数字,因为我必须将一些需要基本算术的软件输出粘合在一起。如果我正在编写一个 shell,我不会假设大多数人需要 4096 位算术。然而,我有两台机器,它们都可以在 BASH 中处理最多 64 位算术,但我的问题是这与 CPU 有何关系。

在 32 位处理器上,BASH 的最大算术能力是 32 位,而在具有某些操作系统和 BASH 的 16 位处理器或 8 位处理器上,最大算术能力是 16 位和 8 位分别?

BASH 手册没有阐明任何限制。

最佳答案

Bash 的内部算术是编译 bash 的目标的位宽,该位宽可能小于运行它的处理器的位宽。具体来说,bash 的内部算术是 intmax_t per this bug-report commentintmax_t 类型为

a signed integer type capable of representing any value of any signed integer type

根据the docs ,并且由编译器定义。因此,bash的运算受到编译环境的限制。即使在 64 位处理器上,为 32 位目标编译的 bash 版本也将限制为 32 位。

详细信息:在 expr.c ,消息人士称

All arithmetic is done as intmax_t integers with no checking for overflow (though division by 0 is caught and flagged as an error).

编辑 这是位宽度的运行时测试,(我认为)仅依赖于 bash 被签名为二进制补码。适用于我的系统 - YMMV。

#!/bin/bash
for((i=1; $i>0; i*=2)); do : ; done    
    # Set the highest-order bit, which is a negative number in signed math.
echo "$(echo "l(-($i))/l(2)"|bc -l)/1+1" | bc
    # Output the position of that bit

内部bc -l计算log2(|$i|),即最高位的索引加上一点点,因为二进制补码范围是零附近不对称。外部 bc 计算该值的上限。 (bc 当没有 -l 运行时会截断除法 - 感谢 this answer )。在我的系统上,输出 64

实证检验:

~$ uname -a                      ---  NOTE: 64-bit Cygwin vvvvvv
CYGWIN_NT-6.3 localhost 2.5.2(0.297/5/3) 2016-06-23 14:29 x86_64 Cygwin
~$ bash --version
GNU bash, version 4.3.46(6)-release (x86_64-unknown-cygwin)
   <cut>       --- NOTE: 64-bit bash ^^^^^^
~$ echo $(( 2 ** 32 ))
4294967296                    <--- so >32 bit
~$ echo $(( 2 ** 64 ))
0                             <--- oops - bigger than 64 bit doesn't work
~$ echo $(( 2 ** 63 ))
-9223372036854775808          <--- but 64 bit does (and is signed)

关于bash - BASH 处理数字的能力是否与处理器位宽成正比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41243574/

相关文章:

linux - AWS EC2 权限被拒绝/usr/local/bin cURL

regex - 匹配 Linux Grep 命令字符串之间的任何内容

python - 自动化 shell 脚本登录 vpn 传递 sudo -S

bash - bash中 'let'的奇怪错误

bash - 如何将 grep 的值分配给变量并与字符串连接?

linux - shell 脚本 - 将所有数据从 stdout 重定向到/dev/null

bash - 如何从awk输出颜色格式

bash - -bash : ghci: command not found (Haskell interactive shell, Haskell 安装)

json - bash JSON with jq - 如何检查空的 JSON 成员?

bash - 当我输入 URL 作为参数时,如何使 bash 脚本正常工作