Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c

string

How do you convert a MAC address within an int array to string in C? For example, I am using the following array to store a MAC address:

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

How do I convert this to a string, like "00:0d:3f:cd:02:5f"?

like image 409
user2131316 Avatar asked May 14 '13 18:05

user2131316


3 Answers

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]);
like image 146
user2233706 Avatar answered Nov 12 '22 21:11

user2233706


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]);
like image 41
www.diwatu.com Avatar answered Nov 12 '22 22:11

www.diwatu.com


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;
}
like image 40
Selso Liberado Avatar answered Nov 12 '22 22:11

Selso Liberado