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

标签 c printf primitive

嗨,我有一个名为 outputSampleRate 的 double 变量,其值为 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 新手而提供的任何意见。

最佳答案

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

如果您想打印 double 的表示形式,请执行以下操作:

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

关于C - 需要解释 printf 选项的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38834876/

相关文章:

matlab - 在 Matlab 中打印非 ASCII/符号字符

c - Mac 上 Xcode 创建的文件存储在哪里?

不能释放双指针

通过 memcpy 复制数组

c - ANSI C : snprintf allocating issue

C编程: How to prevent printf statement from printing out new line values?

Java:为什么要这样定义一个字符呢?

java - 原始值如何存储在对象中以及对象被转换时会发生什么

objective-c - Objective-C 原始数之间的区别

mysql - 多行sql求和;