我怎样才能 printf() 十六进制形式的浮点数?

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

在C中我们可以生成十六进制浮点字面量,我们也可以使用

printf()
以十进制字符串形式输出它们:

printf("%f\n", 0x1.0p8); // Prints 256.00000

如何以保持精度的方式输出十六进制形式的浮点数? (所有十六进制浮点文字都是二元有理数,因此与十进制文字不同,可以用浮点数表示)

printf("%MAGIC\n", 0x1.0p8) // Prints 100.00000

我的研究只发现了与以十六进制形式打印底层表示的字节相关的结果,而不是如何以十六进制形式打印浮点数的值

c floating-point printf
1个回答
1
投票

您可以使用

%a
格式以保留精度的十六进制格式打印浮点数。从手册页

 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.
© www.soinside.com 2019 - 2024. All rights reserved.