标签:
今日有感于编程水平下降,特意练习一下,根据MAC地址字符串,获取MAC地址的2种方法。
#include <stdio.h>
void func1(char *str)
{
unsigned char mac[6] = {0};
sscanf(str, "%2x:%2x:%2x:%2x:%2x:%2x", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
printf("func:%s output: mac=%02x:%02x:%02x:%02x:%02x:%02x \n", __FUNCTION__, mac[0], mac[1], mac[2],mac[3], mac[4],mac[5]);
return ;
}
int getvalue(char c)
{
if(( c >= ‘0‘ ) && ( c <= ‘9‘))
return c - ‘0‘;
else if(( c >= ‘a‘ ) && ( c <= ‘f‘))
return c - ‘a‘ + 10;
else if(( c >= ‘A‘) && ( c <= ‘F‘))
return c - ‘A‘ + 10;
else
return 0;
}
void func2(char *str)
{
/*0f:e2:11:ab:cd:03*/
int i;
unsigned char low;
unsigned char high;
unsigned char mac[6] = {0};
for(i=0; i<6; i++)
{
high = getvalue(str[i*3]);
low = getvalue(str[i*3 + 1]);
mac[i] = (high<<4)+ low;
}
printf("func:%s output: mac=%02x:%02x:%02x:%02x:%02x:%02x \n", __FUNCTION__, mac[0], mac[1], mac[2],mac[3], mac[4],mac[5]);
}
int main(int argc, char** argv) {
func1(argv[1]);
func2(argv[1]);
return 0;
}
运行结果:可见两种方法得到的结果相同
标签:
原文地址:http://www.cnblogs.com/zhouhaibing/p/5668742.html