Mac地址和字符串之间的转换

2018-01-26 10:32:16来源:oschina作者:whoisliang人点击

分享

std::string MacToStr(UINT8 * pMac,const char chKen/* = ':'*/)
{
char szFormat[] = "%02X:%02X:%02X:%02X:%02X:%02X";
int nLen = strlen(szFormat);
if (chKen != ':')
{
for (int i = 2;i < nLen;i += 3)
{
szFormat[i] = chKen;
}
}


char szMac[32] = {0};
sprintf(szMac, szFormat, pMac[0], pMac[1], pMac[2], pMac[3], pMac[4], pMac[5]);
std::string strRet(szMac);
return strRet;

}


UINT8 charToData(const char ch)
{
switch(ch)
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'a':
case 'A': return 10;
case 'b':
case 'B': return 11;
case 'c':
case 'C': return 12;
case 'd':
case 'D': return 13;
case 'e':
case 'E': return 14;
case 'f':
case 'F': return 15;
}
return 0;
}


bool StrToMac(const char * szMac,UINT8 * pMac)
{
const char * pTemp = szMac;
for (int i = 0;i < 6;++i)
{
pMac[i] = charToData(*pTemp++) * 16;
pMac[i] += charToData(*pTemp++);
pTemp++;
}
}


c语言有类似处理:
int hex2num(char c)
{
if (c>='0' && c<='9') return c - '0';
if (c>='a' && c<='z') return c - 'a' + 10;//这里+10的原因是:比如16进制的a值为10
if (c>='A' && c<='Z') return c - 'A' + 10;


printf("unexpected char: %c", c);
return NON_NUM;

}


int str2mac(const charchar * szMac, charchar * pMac)
{
const charchar * pTemp = szMac;
int i;


for (i = 0;i < 6;++i)
{
pMac[i] = hex2num(*pTemp++) * 16;
pMac[i] += hex2num(*pTemp++);
}
return 0;

}


int main()
{
char szValue[32] = "11AABB22CC33 ";
char szBSSID[6] = "";


str2mac(szValue, szBSSID);
printf("Value = %s/n", szValue);
printf("bssid : %02x-%02x-%02x-%02x-%02x-%02x /n",
st_keys.bssid_name[0], st_keys.bssid_name[1],
st_keys.bssid_name[2], st_keys.bssid_name[3],
st_keys.bssid_name[4], st_keys.bssid_name[5]);
return 0;

}
效果:


Value = 11AABB22CC33


bssid = 11-aa-bb-22-cc-33

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台