C语言 为什么 uint8_t 和 uint16_t 的格式说明符相同 (%u)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26362386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:27:37  来源:igfitidea点击:

Why is the format specifier for uint8_t and uint16_t the same (%u)?

cprintfformat-specifiers

提问by Rev1.0

I only found pretty unrelated questions due to the tons of results searching for printf().

由于搜索了大量结果,我只发现了非常不相关的问题printf()

Why does uint8_tnot specify its own format string but any other type does?

为什么不uint8_t指定自己的格式字符串,而其他类型呢?

As far as I understand printf(), it has to know the length of the supplied parameters to be able to parse the variable argument list.

据我了解printf(),它必须知道提供的参数的长度才能解析变量参数列表。

Since uint8_tand uint16_tuse the same format specifier %u, how does printf()"know" how many bytes to process? Or is there somehow an implicit cast to uint16_tinvolved when supplying uint8_t?

由于uint8_tuint16_t使用相同的格式说明符%u,如何printf()“知道”要处理多少字节?或者uint16_t在提供时是否以某种方式隐式转换uint8_t

Maybe I am missing something obvious.

也许我错过了一些明显的东西。

采纳答案by 2501

printf()is a variadic function. Its optional arguments( and only those ) get promoted according to default argument promotions( 6.5.2.2. p6 ).

printf()是一个可变参数函数。它的可选参数(并且只有那些)根据默认参数提升(6.5.2.2.p6)得到提升。

Since you are asking for integers, integer promotions are applied in this case, and types you mention get promoted to int. ( and not unsigned intbecause C )

由于您要求使用整数,因此在这种情况下会应用整数提升,并且您提到的类型将提升为int。(而不是unsigned int因为 C )

If you use "%u"in printf(), and pass it an uint16_tvariable, then the function converts that to an int, then to an unsigned int( because you asked for it with %u ) and then prints it.

如果您"%u"在 printf() 中使用,并向其传递一个uint16_t变量,则该函数会将其转换为 an int,然后转换为 an unsigned int(因为您使用 %u 要求它),然后打印它。

回答by wick

Because %u stands for "unsigned", it well may be uint64_t and is architecture dependent. According to man 3 printf, you may want to use length modifier to get sought behaviour, i.e. %hu (uint16_t) and %hhu (uint8_t).

因为 %u 代表“无符号”,它很可能是 uint64_t 并且依赖于体系结构。根据man 3 printf,您可能希望使用长度修饰符来获得所寻求的行为,即 %hu (uint16_t) 和 %hhu (uint8_t)。