KKsan KKsan - 1 year ago 84
C Question

C - Need explanation on printf options' behavior

Hi I have a double variable named outputSampleRate with value 0x41886a0000000000

I'm trying different combination of printf options and I get very confused by the output.

Here is the code:

printf("\n\noutputSampleRate 0x%16x \n", outputSampleRate);
printf("outputSampleRate 0x%llx \n", outputSampleRate);
printf("outputSampleRate 0x%.llx \n", outputSampleRate);
printf("outputSampleRate 0x%.16x \n", outputSampleRate);
printf("outputSampleRate 0x%16llx \n", outputSampleRate);
printf("outputSampleRate 0x%.16llx \n\n", outputSampleRate);

Here is the printout on console:

outputSampleRate %llx 0x 0
outputSampleRate %16x 0x41886a0000000000
outputSampleRate %.llx 0x41886a0000000000
outputSampleRate %.16x 0x0000000000000000
outputSampleRate %16llx 0x41886a0000000000
outputSampleRate %.16llx 0x41886a0000000000

Please correct me if I'm wrong:

%llx print as long long (64 bit) in hex representation
%16x print 16 digits, ignore leading 0s in hex representation
%.llx ????what is this?
%.16x print at least 16 digits in hex repesentation
%16llx print 16 digits as a long long in hex representation
%.16llx print at least 16 digits as a long long in hex representation

Besides, I have the following questions:

1. How does %llx give me 0x 0 ?
2. Why %.llx and %.16x behave differently ?

Thank you for any input to save this C newbie.

R.. R..
Answer Source

%llx does not mean "print as long long in hex". It means the argument is (has type) long long. If you violate this requirement, your program has undefined behavior.

If you want to print the representation of a double, do something like:

double x;
uint64_t x_repr;
memcpy(&x_repr, &x, sizeof x_repr);
printf("%" PRIx64 "\n", x_repr);