This code:
#include <stdio.h>
int main(void)
{
printf("%a\n", 1.0);
printf("%x\n", 93);
}
outputs:
0x1p 0
5d
Why not 0x5d
?
Does someone know the rationale?
Note: this question is not exactly the same since it is about %#x
.
CodePudding user response:
I think you just have option to have 0x or not. When you use %x
, you receive the raw hexadecimal number. But when you use %#x
, you receive the hex number with the 0x
prefix. What you choose depends on situation.
CodePudding user response:
"%a"
, "%A"
leads with "0x"
, "0X"
to help distinguish it from decimal output of "%f"
, "%e"
, "%g"
, "%F"
, ...
"%a"
came along well after memory prices dropped.
"%x"
leads without a prefix as often code needs to concatenate hex output as in printf("xx", a32, b32);
It is trivial to prefix with "0x"
then as in "0xxx"
. Not prefixing hex output as the default was certainly more common, back in the day (1970s) as every bytes costs.
Using #
with "%x"
as in "%#x"
does not always prefix output. The prefix occurs (in the same case as digits) when the value is non-zero.
For clarity, I find a lower case x
and uppercase hex digits useful.
// v------ lower --------v
printf("0xX\n", 0u-1u); // 0xFFFFFFFF
// ^-- upper ---------^^^^^^^^
CodePudding user response:
As explained by @Jack05, the '#' character makes the difference. The manual of printf explains the conversion:
Each conversion specification is introduced by the character %, and ends with a conversion specifier. In between there may be (in this order) zero or more flags, an optional minimum field width, an optional precision and an optional length modifier.
The overall syntax of a conversion specification is:%[$][flags][width][.precision][length modifier]conversion
If the flag character is set with '#', then:
For x and X conversions, a nonzero result has the string "0x" (or "0X" for X conversions) prepended to it.
For the 'a' or 'A' conversion,
the double argument is converted to hexadecimal notation (using the letters abcdef) in the style [-]0xh.hhhhp±d; for A conversion the prefix 0X, the letters ABCDEF