Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Mac string to a Byte address in C

Tags:

c

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

like image 690
user1727270 Avatar asked Oct 07 '12 20:10

user1727270


1 Answers

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;
}
like image 64
renonsz Avatar answered Sep 22 '22 09:09

renonsz