MAC 地址解析

MAC address parsing

本文关键字:地址解析 MAC      更新时间:2023-10-16

我有一个像"6F:e:5B:7C:b:a"这样的MAC地址,我想解析并在:e:,:b:,:a之前插入隐式零。

我目前无法使用 Boost,但我有一个粗略的解决方案。解决方案在":"上拆分。然后我计算字符之间的字符,如果只有一个,我会在前面插入一个零。

我想知道是否有人有更快的方法?

对于快速和肮脏:

if (sscanf(text, "%x:%x:%x:%x:%x:%x",
           &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) != 6) {
    // handle error
}

请注意,它不会检查数字是否真的是十六进制。sscanf() 的常规预防措施适用。

首先,

您可以使用脚本将char转换为int非常快,因此:

unsigned char hex_to_int(const char c)
{
    if( c >= 'a' && c <= 'f'){
        return c - 'a' + 10;
    }
    if( c >= 'A' && c <= 'F'){
        return c - 'A' + 10;
    }
    if( c >= '0' && c <= '9'){
        return c - '0';
    }
    return 0;
}

然后,您可以创建循环来迭代字符串:

unsigned char mac[6]; /* Resulting mac */
int i; /* Iteration number */
char *buffer; /* Text input - will be changed! */
unsigned char tmp; /* Iteration variable */
for( i = 0; i < 6; ++i){
    mac[i] = 0;
    /*
     * Next separator or end of string 
     * You may also want to limit this loop to just 2 iterations
     */
    while( ((*buffer) != '') && ((*buffer) != ':'){
        mac[i] <<= 4;
        mac[i] |= hex_to_int( *buffer);
        ++buffer;
    }
}
if( (i != 6) || (*buffer != NULL)){
    // Error in parsing, failed to get to the 6th iteration
    // or having trailing characters at the end of MAC
}

此函数不执行任何错误检查,但它可能是您将获得的最快解决方案。