How do I printf() a uint16_t?

吃可爱长大的小学妹 提交于 2019-12-04 00:24:37

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.

You should use the style of inttypes.h but define the symbols yourself. For example:

#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.

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.

short int is the smallest at least 16 bits long so convert the value to unsigned short int and print it with %hu.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!