Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a MAC address (in string) to array of integers? [closed]

Tags:

arrays

c

string

How do I convert a MAC address within a string to an array of integers in C?

For example, I have the following string that stores a MAC address:

00:0d:3f:cd:02:5f

How do I convert this to:

uint8_t array[6] = {0x00, 0x0d, 0x3f, 0xcd, 0x02, 0x5f}
like image 698
Lior Avramov Avatar asked Dec 12 '13 20:12

Lior Avramov


2 Answers

uint8_t bytes[6];
int values[6];
int i;

if( 6 == sscanf( mac, "%x:%x:%x:%x:%x:%x%*c",
    &values[0], &values[1], &values[2],
    &values[3], &values[4], &values[5] ) )
{
    /* convert to uint8_t */
    for( i = 0; i < 6; ++i )
        bytes[i] = (uint8_t) values[i];
}

else
{
    /* invalid mac */
}

[EDIT: Added %c at the end of the format string to reject excess characters in the input, based on D Krueger's suggestion.]

like image 130
TypeIA Avatar answered Nov 11 '22 15:11

TypeIA


This is one of the few places where I'd consider using something like sscanf() to parse the string, since MAC addresses tend to be formatted very rigidly:

char str[] = "00:0d:3f:cd:02:5f";
uint8_t mac_addr[6];
if (sscanf(str, "%x:%x:%x:%x:%x:%x",
           &mac_addr[0],
           &mac_addr[1],
           &mac_addr[2],
           &mac_addr[3],
           &mac_addr[4],
           &mac_addr[5]) < 6)
{
    fprintf(stderr, "could not parse %s\n", str);
}
like image 3
Tim Pierce Avatar answered Nov 11 '22 17:11

Tim Pierce