gpt4 book ai didi

bash - bash 中数字的表示和 bash 中十六进制数的 printf

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

我想了解数字( double )在 bash 中是如何表示的,以及当我在 bash 中以十六进制格式打印数字时会发生什么。

根据 IEEE 754 标准,double 应由 64 位表示:52 位(13 个十六进制数)表示有效数,11 位表示指数,1 位表示符号。

为了检查它,我编写了一个简单的 C 程序,将 hex 转换为 dec(使用 printf)。

include <stdio.h>
int main(int argc, char **argv)
{
printf("hex read = %40.24a\n", 0x1.000010C6F7A0B5E1Fp+0);
}

用 gcc 4.2.1 编译,我得到

hex read =          0x1.000010c6f7a0b00000000000p+0

从这个结果我得出结论,正如我所期望的那样,有效数字是由 13 个十六进制数字 000010c6f7a0b 定义的。

现在我转向 bash 并使用以下脚本:

#!/bin/bash
echo "hex read = 0x"$1
printf "hex =%80.70a\n" "0x"$1
printf "hex -> dec=%80.70f\n" `echo "0x"$1`

GNU 庆典 3.2.48

$ bash hex2dec 1.000010C6F7A0B5E1F
hex read = 0x1.000010C6F7A0B5E1F
hex = 0x1.000010c6f7a0b000000000000000000000000000000000000000000000000000000000p+0
hex -> dec= 1.0000009999999999177333620536956004798412322998046875000000000000000000

所以一切都如我所料:13 个十六进制数字定义了数字的有效数字。

GNU bash 4.1.5

$ bash hex2dec 1.000010C6F7A0B5E1F
hex read = 0x1.000010C6F7A0B5E1F
hex = 0x8.00008637bd05af10000000000000000000000000000000000000000000000000000000p-3
hex -> dec= 1.0000009999999999993737856418540843606024282053112983703613281250000000

这不是我所期望的!

问题 1 为什么在 GNU bash 4.1.5 中 double 由 16 位十六进制数字表示(而不是根据 IEEE 754 的 13 位)?

问题2 为什么printf "%a"在不同的bash版本中以不同的格式表示十六进制数(bash 3.2.48 0x1.hh...hp+ d 和 bash 4.1.5 0xh.hh...hp+d?)。 printf 不应该在两个 bash 版本中遵循相同的标准并且被 http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html 重新定义吗? ?

最佳答案

答案 1 当前 bash 的 printf在 x86 上使用 long double 按照 IEEE 754 进行输入/输出转换(参见 Extended and extendable precision formats , x86 Extended Precision Format 和 bash 的 printf 对 floatmax_t 的定义),类似于程序

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
printf("%La\n", strtold("0x1.000010C6F7A0B5E1F", NULL));
}
  • 它的输出是 0x8.00008637bd05af1p-3

答案2 Bash最终使用的是C库的printf;上面 C 程序的输出确实遵循您引用的标准:

there is one hexadecimal digit (which shall be non-zero if the argument is a normalized floating-point number and is otherwise unspecified) before the decimal-point character

关于bash - bash 中数字的表示和 bash 中十六进制数的 printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14641766/

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