首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MAC地址解析

MAC地址解析
EN

Stack Overflow用户
提问于 2012-11-14 20:09:27
回答 2查看 3.6K关注 0票数 0

我有一个类似于"6F:e:5B:7C:b :a“的MAC地址,我希望解析该地址并在:e:,:b:,:A之前插入隐式零。

我现在不能使用Boost,但我有一个粗略的解决方案。解决方案在“:”上分成两部分。然后我计算中间的字符数,如果只有一个,我会在前面插入一个零。

我想知道有没有更快的方法?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-11-14 20:37:28

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

代码语言:javascript
复制
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;
}

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

代码语言:javascript
复制
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) != '\0') && ((*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
}

这个函数不做任何错误检查,但它可能是你能得到的最快的解决方案。

票数 1
EN

Stack Overflow用户

发布于 2014-09-20 04:55:50

对于快速和肮脏的人:

代码语言:javascript
复制
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()的常规预防措施适用。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13378567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档