将MAC字符串/十六进制相互转换(已测)
时间:2010-03-18 来源:newcch
int macStrToMacNum(unsigned char *macstr,unsigned char *macAddrNum)
{
int i = 0,j = 0,value;
unsigned char str_tmp[6]="\0",tmp='\0';
if(macstr == NULL || macAddrNum == NULL)
{
printf("mac null !\n");
return -1;
}
for(i=0;i<6;i++)
{
bzero(str_tmp,sizeof(str_tmp));
memcpy(str_tmp,macstr,2*sizeof(char));
macstr +=2;
macAddrNum[i]='\0';
for(j=strlen((char *)str_tmp)-1;j>=0;j--)
{
switch(tolower(str_tmp[j]))
{
case '1' : value = 0x1; break;
case '2' : value = 0x2; break;
case '3' : value = 0x3; break;
case '4' : value = 0x4; break;
case '5' : value = 0x5; break;
case '6' : value = 0x6; break;
case '7' : value = 0x7; break;
case '8' : value = 0x8; break;
case '9' : value = 0x9; break;
case 'a' : value = 0xa; break;
case 'b' : value = 0xb; break;
case 'c' : value = 0xc; break;
case 'd' : value = 0xd; break;
case 'e' : value = 0xe; break;
case 'f' : value = 0xf; break;
case '0' : value = 0x0; break;
default :
printf("error str_tmp[j]=%c \n!",str_tmp[j]);//shiner
return -1;
}
macAddrNum[i] |= (unsigned char )(value << ((strlen((char *)str_tmp)-1-j)*4));
}
}
return 0;
}
int macNumToStr(char *macAddr, char *str) {
if ( macAddr == NULL ) return -1;
if ( str == NULL ) return -1; sprintf(str, "%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x",
(unsigned char ) macAddr[0], (unsigned char ) macAddr[1], (unsigned char ) macAddr[2],
(unsigned char ) macAddr[3], (unsigned char ) macAddr[4], (unsigned char ) macAddr[5]); return 0;
}
相关阅读 更多 +