C - 需要解释printf选项'行为

时间:2016-08-08 17:06:05

标签: c printf primitive

您好我有一个名为outputSampleRate的双变量,其值为0x41886a0000000000

我正在尝试不同的printf选项组合,我对输出感到非常困惑。

以下是代码:

    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);

以下是控制台上的打印输出:

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

如果我错了,请纠正我:

%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

此外,我还有以下问题:

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

感谢您保存此C新手的任何输入。

1 个答案:

答案 0 :(得分:1)

%llx并不意味着“以十六进制打印为long long”。这意味着参数是(有类型)long long 。如果您违反此要求,您的程序会有未定义的行为。

如果要打印double的表示,请执行以下操作:

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