Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The format specifier %a for printf() in C

Tags:

I am reading a C language book, it said %f, %e, %g, %a were printf chars used for float and double data types. Currently I can understand %f, %e, %g completely.

When do I need use %a to print float and double type data ?

Can you please show me an example.

like image 774
Nano HE Avatar asked Jan 28 '11 09:01

Nano HE


People also ask

What is %s %d %F in C?

%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].

What are the format specifiers for the print () method?

Let's look at the available format specifiers available for printf : %c character. %d decimal (integer) number (base 10) %e exponential floating-point number.

What is %f in printf in C?

The f in printf stands for formatted, its used for printing with formatted output.


1 Answers

The %a formatting 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.

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 p is for power-of-two the floating-point number is raised to). In this case, "1.91EB8616" is "1.570000052452087410". Multiply this by the "21", and you get "3.14000010490417510".

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.

like image 57
unwind Avatar answered Oct 06 '22 01:10

unwind