How to Serial.print unsigned char xxxx[] ?

In my sketch I have this that stores serial numbers;

unsigned char login[][8] =
{
{0x12, 0x22, 0x71, 0x16, 0x13, 0x74, 0x00, 0x00},
{0x10, 0x42, 0x71, 0x11, 0x15, 0x36, 0x00, 0x00},
};

How do I Serial.print (login[i]) each serial number to the console?

so it would print it as either

0x12, 0x22, 0x71, 0x16, 0x13, 0x74, 0x00, 0x00

or

1222711613740000

with two nested for loops.

try something like this

unsigned char login[][8] = {
  {0x12, 0x22, 0x71, 0x16, 0x13, 0x74, 0x00, 0x00},
  {0x10, 0x42, 0x71, 0x11, 0x15, 0x36, 0x00, 0x00}
};

void setup() {
  Serial.begin(115200);

  for (int i = 0; i < sizeof login / sizeof * login; i++) {
    Serial.print("login["); Serial.print(i); Serial.print("] = {");
    for (int j = 0; j < sizeof login[0] / sizeof * login[0]; j++) {
      Serial.print("0x");  // Print the "0x" prefix
      if (login[i][j] < 0x10) Serial.write('0');
      Serial.print(login[i][j], HEX);
      if (j < 7) Serial.write(", ");
    }
    Serial.println("}");  // Print a newline after each serial number
  }
}

void loop() {}

you should see in the serial monitor (set at 115200 bauds)

login[0] = {0x12, 0x22, 0x71, 0x16, 0x13, 0x74, 0x00, 0x00}
login[1] = {0x10, 0x42, 0x71, 0x11, 0x15, 0x36, 0x00, 0x00}
1 Like
void disp (
    unsigned char *buf,
    int            nByte )
{
    char s[10];

    sprintf (s, "0x%02x", buf [0]);
    Serial.print (s);

    for (int n = 1; n < nByte; n++) {
        sprintf (s, ", 0x%02x", buf [n]);
        Serial.print (s);
    }
    Serial.println (s);
}

unsigned char login[][8] = {
    {0x12, 0x22, 0x71, 0x16, 0x13, 0x74, 0x00, 0x00},
    {0x10, 0x42, 0x71, 0x11, 0x15, 0x36, 0x00, 0x00},
};

void
setup (void)
{
    Serial.begin (9600);

    disp (&login [1][0], 8);
    disp (&login [0][0], 8);
}

void loop (void) { }

1 Like

Thank you both for your help, that's fantastic.