How do you convert a MAC address (in an array) to string in C?

You could do this:

char macStr[18];
int array[6] = {0x00, 0x0d, 0x3f, 0xcd, 0x02, 0x5f};

snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
         array[0], array[1], array[2], array[3], array[4], array[5]);

If you want an uppercase string, use uppercase 'X':

snprintf(macStr, sizeof(macStr), "%02X:%02X:%02X:%02X:%02X:%02X",
         array[0], array[1], array[2], array[3], array[4], array[5]);

whithout using snprintf, but that's just for fun....

#define MAC_LEN 6

static const char _mac[MAC_LEN] = { 0xBC, 0xDD, 0xC2, 0xF0, 0x2E, 0x06 };

int main(void){

char mac[MAC_LEN*2 + 1] = {0}; // added null char

int j = 0;
for( int i = 0;  i < sizeof(_mac) ; i++ )
{
    j = i * 2;
    mac[j] = (((_mac[i] & 0xF0)>>4)&0xF) ;
    mac[j] += (mac[j] <= 9) ? '0' : ('A' - 10);
    j++;
    mac[j] = (_mac[i] & 0x0F);
    mac[j] += (mac[j] <= 9) ? '0' : ('A' -10);
}

printf("Hello World!, my mac address : %s\n", mac);

fflush(stdout);

return 0;
}

unsigned char array[6] = {0x00, 0x0d, 0x3f, 0xcd, 0x02, 0x5f};//or BYTE

char str[19];
sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x",array[0], 
        array[1], array[2], array[3], array[4],array[5]);

Tags:

C

Arrays

String