C语言 打印 uint8_t

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14358967/
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 05:03:30  来源:igfitidea点击:

printing the uint8_t

cdebugging

提问by Saeed

I have uint8_t orig[ETH_ALEN];

我有 uint8_t orig[ETH_ALEN];

How can I print it using __printf(3, 4)

我如何使用它打印它 __printf(3, 4)

which is defined as #define __printf(a, b) __attribute__((format(printf, a, b)))

定义为 #define __printf(a, b) __attribute__((format(printf, a, b)))

the Orig should be ethernet hardware address.

Orig 应该是以太网硬件地址。

回答by

Use C99 format specifiers:

使用 C99 格式说明符:

#include <inttypes.h>

printf("%" PRIu8 "\n", orig[0]);

回答by unwind

You need to construct a format string that's suitable. The printf()function has no way of printing an array in one go, so you need to split it and print each uint8_t:

您需要构造一个合适的格式字符串。该printf()函数无法一次性打印数组,因此您需要拆分它并打印每个uint8_t

__printf("MAC: %02x:%02x:%02x:%02x:%02x:%02x\n",
         orig[0] & 0xff, orig[1] & 0xff, orig[2] & 0xff,
         orig[3] & 0xff, orig[4] & 0xff, orig[5] & 0xff);

The & 0xffis to ensure onlu 8 bits is sent to printf(); they shouldn't be needed for an unsigned type like uint8_tthough so you can try without too.

& 0xff是为了确保发送 8 位 onlu printf();像uint8_t这样的无符号类型不应该需要它们,因此您也可以尝试不使用它们。

This assumes a regular 48-bit MAC, and prints using the conventionalcolon-separated hex style.

这假设使用常规的 48 位 MAC,并使用传统的冒号分隔的十六进制样式进行打印。