"%#x" 在 printf 系列函数的格式字符串中等同于 "0x%x" 吗?

huangapple go评论101阅读模式
英文:

Is "%#x" equivalent to "0x%x" in the format string of printf family functions?

问题

这两个函数调用等效吗?(假设变量 x 的类型为 unsigned int

printf ("%#x\n", x);
printf ("0x%x\n", x);

以及以下两个函数调用:

printf ("%#.8x\n", x);
printf ("0x%08x\n", x);

为什么一些嵌入式程序偏向于使用后者而不是前者?

英文:

Are these two function calls equivalent? ( Assuming that the type of variable x is unsigned int)

printf ("%#x\n", x);
printf ("0x%x\n", x);

And the following two function calls:

printf ("%#.8x\n", x);
printf ("0x%08x\n", x);

Why do some embedded programs prefers the latter one to the former one?

答案1

得分: 2

从C标准7.9.16.1第6段中关于fprintf中的#

结果被转换为“替代形式”...对于x(或X)转换,非零结果前缀为0x(或0X)。

所以,%#x 将在非零结果前缀为 0x。所以它与 0x%x 相同,除非结果为零。

英文:

From the C standard 7.9.16.1 para 6, on # in fprintf:

> The result is converted to an ‘‘alternative form’’... For x (or X) conversion, a nonzero
> result has 0x (or 0X) prefixed to it.

So there you have it: %#x prefixes 0x to any non-zero result. So it's the same as 0x%x except when the result is zero.

huangapple
  • 本文由 发表于 2023年5月6日 15:33:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76187674.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定