I want to take MAC address from command line, so I got it as string...how do I can convert this 17 byte MAC string like \"00:0d:3f:cd:02:5f\" to 6 byte MAC Address in C
On a C99-conformant implementation, this should work
unsigned char mac[6];
sscanf(macStr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
Otherwise, you'll need:
unsigned int iMac[6];
unsigned char mac[6];
int i;
sscanf(macStr, "%x:%x:%x:%x:%x:%x", &iMac[0], &iMac[1], &iMac[2], &iMac[3], &iMac[4], &iMac[5]);
for(i=0;i<6;i++)
mac[i] = (unsigned char)iMac[i];
Without built-in functions and error handling simply:
unsigned char mac[6];
for( uint idx = 0; idx < sizeof(mac)/sizeof(mac[0]); ++idx )
{
mac[idx] = hex_digit( mac_str[ 3 * idx ] ) << 4;
mac[idx] |= hex_digit( mac_str[ 1 + 3 * idx ] );
}
Input is actually 3*6 bytes with \0
.
unsigned char hex_digit( char ch )
{
if( ( '0' <= ch ) && ( ch <= '9' ) ) { ch -= '0'; }
else
{
if( ( 'a' <= ch ) && ( ch <= 'f' ) ) { ch += 10 - 'a'; }
else
{
if( ( 'A' <= ch ) && ( ch <= 'F' ) ) { ch += 10 - 'A'; }
else { ch = 16; }
}
}
return ch;
}