如何手动将浮点数的fprintf十六进制表示转换为十进制

问题描述 投票:0回答:1

fprintf 和 snprintf 中浮点数的十六进制表示形式似乎采用以下形式(使用 A 作为格式说明符): 0XH.HHHHP[+-]d ,其中小数点右侧的十六进制位数为变量。

我找到了至少一本解释这种格式的手册:

https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/printf.3.html

  aA     The double argument is rounded and converted to hexadecimal notation in the 
         style [-]0xh.hhhp[+-]d, where the number of digits
         after the hexadecimal-point character is equal to the precision
         specification.  If the precision is missing, it is taken as
         enough to represent the floating-point number exactly, and no
         rounding occurs.  If the precision is zero, no hexadecimal-point
         character appears.  The p is a literal character `p', and the
         exponent consists of a positive or negative sign followed by a
         decimal number representing an exponent of 2.  The A conversion
         uses the prefix ``0X'' (rather than ``0x''), the letters
         ``ABCDEF'' (rather than ``abcdef'') to represent the hex digits,
         and the letter `P' (rather than `p') to separate the mantissa and
         exponent.

         Note that there may be multiple valid ways to represent floating-point 
         point numbers in this hexadecimal format.  For example,
         0x3.24p+0, 0x6.48p-1 and 0xc.9p-2 are all equivalent.  The format
         chosen depends on the internal representation of the number, but
         the implementation guarantees that the length of the mantissa
         will be minimized.  Zeroes are always represented with a mantissa
         of 0 (preceded by a `-' if appropriate) and an exponent of +0.

我不明白这个解释。我相信我理解将浮点数转换为二进制的一般方法:包括一个符号位,一个指数位,指的是二进制中第一个有效数字的位置,并使用其余位来表示右侧的数字二进制的十进制。

我不明白的是如何使用这种格式完成此操作,例如:

小数点左边的字符代表什么?

小数点缺失是什么意思?

小数点右边的字符代表什么?

为什么字母P总是在那里?

任何人都可以向我展示一些与此表示形式和浮点数相互转换的示例吗?

c floating-point hex
1个回答
0
投票

我找到了至少一本解释这种格式的手册......

您应该查看C 标准以获取此类信息。

小数点左边的字符代表什么?

在十进制中,34.5•100、3.45•101和.345•100是相同的数字。在十进制中,9A.B16•160、9.AB16•161、.9AB16•162 是相同的数字。在 [-]0xh.hhhhp±d 的样式描述中,h.hhhh 部分只是告诉您它将使用该点左侧的一位十六进制数字对其进行格式化(并调整指数以匹配).

小数点缺失是什么意思?

这只是一种审美选择。当分数位置没有数字时,小数点右侧不需要有小数点来指示分数位置的开始位置。然而,

%a
格式大多用于显示整个浮点值,因此我们通常让所有数字都出现,并且不将精度设置为零。

小数点右边的字符代表什么?

它们是分数位置的数字,与小数表示法相同。例如,十六进制数字 123.45616 表示 1•162 + 2•161 + 3•160 + 4•16−1 + 5•16−2 + 6• 16−3.

为什么字母P总是在那里?

它代表“幂”,标志着指数的开始。对于输出,如果指数为零,我们可以抑制它。然而,选择这种输出格式是为了匹配源代码中十六进制文字的形式,对于这些,我们至少需要整数中的“p”来区分十六进制整数文字

0x3
与十六进制浮点文字
0x3p0 
.

© www.soinside.com 2019 - 2024. All rights reserved.