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
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;
}
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