Linux下用C语言将一个字符串格式(char*)的MAC地址转换为十六进制数组

http://blog.csdn.net/hbl0307106015/article/details/8818098

#include
#include

unsigned char a2x(const char c)
{
switch(c) {
case '0'...'9':
return (unsigned char)atoi(&c);
case 'a'...'f':
return 0xa + (c-'a');
case 'A'...'F':
return 0xa + (c-'A');
default:
goto error;
}
error:
exit(0);
}

/*convert a string,which length is 18, to a macaddress data type.*/
#define MAC_LEN_IN_BYTE 6
#define COPY_STR2MAC(mac,str)  \
int i; \
do { \
for(i = 0; i < MAC_LEN_IN_BYTE; i++) {\
  mac[i] = (a2x(str[i*3]) << 4) + a2x(str[i*3 + 1]);\
}\
} while(0)


int main(int argc, char **argv)
{
unsigned char macaddr[8] = {0};
char macaddr_str[18] = "8e:b2:cf:89:00:4a";
COPY_STR2MAC(macaddr,macaddr_str);
printf("0x%02x %02x\n",macaddr[0],macaddr[1]);
printf("%02x %02x\n",macaddr[2],macaddr[3]);
printf("%02x %02x\n",macaddr[4],macaddr[5]);

return 0;
}

你可能感兴趣的:(Linux下用C语言将一个字符串格式(char*)的MAC地址转换为十六进制数组)