我有一个类似于"6F:e:5B:7C:b :a“的MAC地址,我希望解析该地址并在:e:,:b:,:A之前插入隐式零。
我现在不能使用Boost,但我有一个粗略的解决方案。解决方案在“:”上分成两部分。然后我计算中间的字符数,如果只有一个,我会在前面插入一个零。
我想知道有没有更快的方法?
发布于 2012-11-14 20:37:28
首先,您可以使用可以非常快速地将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) != '\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
}这个函数不做任何错误检查,但它可能是你能得到的最快的解决方案。
发布于 2014-09-20 04:55:50
对于快速和肮脏的人:
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()的常规预防措施适用。
https://stackoverflow.com/questions/13378567
复制相似问题