C语言 C 中 printf() 的格式说明符 %a
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4826842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The format specifier %a for printf() in C
提问by Nano HE
I am reading a C language book, it said %f, %e, %g, %awere printf chars used for floatand doubledata types. Currently I can understand %f, %e, %gcompletely.
我读C语言的书,它说%f, %e, %g, %a是用于printf的字符float和double数据类型。目前我可以%f, %e, %g完全理解。
When do I need use %ato print floatand doubletype data ?
我什么时候需要使用%a来打印float和double输入数据?
Can you please show me an example.
你能给我举个例子吗?
回答by unwind
The %aformatting specifier is new in C99. It prints the floating-point number in hexadecimal form. This is not something you would use to present numbers to users, but it's very handy for under-the-hood/technical use cases.
该%a格式说明符在C99是新的。它以十六进制形式打印浮点数。这不是你用来向用户展示数字的东西,但它对于底层/技术用例非常方便。
As an example, this code:
例如,此代码:
printf("pi=%a\n", 3.14);
prints:
印刷:
pi=0x1.91eb86p+1
The excellent article linked in the comments explains that this should be read "1.91EB8616* 21" (that is, the pis for power-of-twothe floating-point number is raised to). In this case, "1.91EB8616" is "1.570000052452087410". Multiply this by the "21", and you get "3.14000010490417510".
在评论中链接的优秀的文章解释说,这应读“1.91EB86 16* 2 1”(即,p是power-of-two浮点数提高到)。在这种情况下,“1.91EB86 16”是“1.5700000524520874 10”。将其乘以“2 1”,得到“3.140000104904175 10”。
Note that this also has the useful property of preserving all bits of precision, and presenting them in a robust way. For instance you could use this to serialize floating point numbers as text, and not have to worry about repeating/infinite decimals.
请注意,这也具有保留所有精度位并以稳健方式呈现它们的有用属性。例如,您可以使用它来将浮点数序列化为文本,而不必担心重复/无限小数。
Also note that strtod()can convert floating point numbers in hexadecimal form back to actual numbers. Not 100% sure about sscanf()and friends, the documentation was not very clear and I've never used that.
另请注意, strtod()可以将十六进制形式的浮点数转换回实际数字。不是 100% 确定sscanf()和朋友,文档不是很清楚,我从未使用过。
回答by Daniel
As far as an example of why you would want to use the hex representation, you may want to use %a to precisely represent a floating point value being sent to another machine for processing.
至于为什么要使用十六进制表示的示例,您可能希望使用 %a 来精确表示发送到另一台机器进行处理的浮点值。
We're using this currently for unit testing an embedded controller by sending data from a simulated plant model that is emulating sensors and actuators to the embedded processor via a UART where the embedded processor does it's control processing and returns feedback (again, float represented as %a) back to the plant model to close the loop.
我们目前正在使用它来对嵌入式控制器进行单元测试,方法是将模拟传感器和执行器的模拟工厂模型中的数据通过 UART 发送到嵌入式处理器,其中嵌入式处理器进行控制处理并返回反馈(同样,浮点数表示为%a) 返回工厂模型以关闭循环。

