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}
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.]
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With