C语言 我如何 printf() 一个 uint16_t?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29112878/
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
How do I printf() a uint16_t?
提问by user9993
I need to use printf() to print a uint16_t. This SO answer (How to print uint32_t and uint16_t variables value?) says I need to use inttypes.h.
我需要使用 printf() 来打印 uint16_t。这个 SO 答案(如何打印 uint32_t 和 uint16_t 变量值?)说我需要使用 inttypes.h。
However, I'm working on an embedded system and inttypes.h is not available. How do I print a uint16_t when the format specifier for a uint16_t is not available?
但是,我正在研究嵌入式系统,并且 inttypes.h 不可用。当 uint16_t 的格式说明符不可用时,如何打印 uint16_t?
回答by Jeff Learman
You should use the style of inttypes.h but define the symbols yourself. For example:
您应该使用 inttypes.h 的样式,但自己定义符号。例如:
#define PRIu8 "hu"
#define PRId8 "hd"
#define PRIx8 "hx"
#define PRIu16 "hu"
#define PRId16 "hd"
#define PRIx16 "hx"
#define PRIu32 "u"
#define PRId32 "d"
#define PRIx32 "x"
#define PRIu64 "llu" // or possibly "lu"
#define PRId64 "lld" // or possibly "ld"
#define PRIx64 "llx" // or possibly "lx"
Figure them out for your machine and use them. Take a look at others in inttypes.h and figure which you will need.
为您的机器找出它们并使用它们。查看 inttypes.h 中的其他内容,并确定您需要哪些内容。
This way, your code will be more portable. I've been doing embedded systems work since the late 70's. Trust me: portability is important.
这样,您的代码将更具可移植性。自 70 年代末以来,我一直在从事嵌入式系统工作。相信我:便携性很重要。
回答by M.M
An obvious way is:
一个明显的方法是:
printf("%u\n", (unsigned int)x);
The unsigned int is guaranteed to be at least 16 bits, so this is not a lossy conversion.
unsigned int 保证至少为 16 位,因此这不是有损转换。
回答by StenSoft
short intis the smallest at least 16 bits long so convert the value to unsigned short intand print it with %hu.
short int是最小的至少 16 位长,因此将值转换为unsigned short int并用%hu.

