9

I have uint8_t orig[ETH_ALEN];

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

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

the Orig should be ethernet hardware address.

Saeed
  • 550
  • 1
  • 7
  • 12
  • 2
    `%u` works for any `uintN_t`, I think, or at least `uint8_t`. – rvighne Aug 23 '14 at 03:05
  • 2
    Possible duplicate of [Format specifiers for uint8\_t, uint16\_t, ...?](https://stackoverflow.com/questions/6993132/format-specifiers-for-uint8-t-uint16-t) – phuclv Apr 30 '19 at 03:55

2 Answers2

21

Use C99 format specifiers:

#include <inttypes.h>

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

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("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 & 0xff is to ensure onlu 8 bits is sent to printf(); they shouldn't be needed for an unsigned type like uint8_t though so you can try without too.

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

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 1
    `uint8_t` is guaranteed to only have 8 bits so the mask is unnecessary. But, even then more than 8 bits will be sent anyway because `printf` is variadic so they will all be promoted to `unsigned int`. – dreamlax Jan 16 '13 at 13:27
  • 1
    @dreamlax All values of a `uint8_t` are representable as an `int`, so the integer promotions [and hence default argument promotions] will promote `uint8_t` to `int`. – Daniel Fischer Jan 16 '13 at 13:29
  • @DanielFischer: D'oh that's what I meant... the `unsigned` came out of nowhere. What I meant was more than 8 bits will be given to printf because of integer promotion. – dreamlax Jan 16 '13 at 13:30