#include <string>
#include <iostream>
using namespace std;
class MAC_Convertor
{
public:
static int ConvertXDigit2Number(const char * text)
{
int retval;
if (*text <= '9' && *text >= '0')
retval = (*text - '0');
else if (*text <= 'F' && *text >= 'A')
retval = (*text - 'A' + 10);
else if (*text <= 'f' && *text >= 'a')
retval = (*text - 'a' + 10);
retval <<= 4;
text++;
if (*text <= '9' && *text >= '0')
retval |= (*text - '0');
else if (*text <= 'F' && *text >= 'A')
retval |= (*text - 'A' + 10);
else if (*text <= 'f' && *text >= 'a')
retval |= (*text - 'a' + 10);
return retval;
}
//替换字符串
static std::string& StrReplaceSome(std::string & target, const std::string & replaceOld, const std::string & replaceNew)
{
for(std::string::size_type pos = 0; pos!=std::string::npos; pos+=replaceNew.length())
{
if((pos = target.find(replaceOld,pos))!=std::string::npos)
target.replace(pos,replaceOld.length(),replaceNew);
else
break;
}
return target;
}
//convert UnDelimited String to byte
static int UndelimitedStr2Byte(const std::string& undelimitedMac, void * byteMac)
{
int len = 0;
const char * pUndelimitedMac = undelimitedMac.c_str();
unsigned char * buf = (unsigned char *)byteMac;
while (len < 6 && *pUndelimitedMac)
{
if (isxdigit(pUndelimitedMac[0]) && isxdigit(pUndelimitedMac[1]))
{
*buf++ = ConvertXDigit2Number(pUndelimitedMac);
pUndelimitedMac += 2;
len++;
continue;
}
pUndelimitedMac++;
}
return (len == 6)? 0: -1;
}
//convert Delimited String to byte
static int DelimitedStr2Byte(const std::string& delimitedMac, void * byteMac)
{
std::string temp(delimitedMac);
StrReplaceSome(temp,"-","");
return UndelimitedStr2Byte(temp, byteMac);
}
//convert byte to Delimited String
static std::string Byte2DelimitedStr(const unsigned char byteMac[6])
{
char DelimitedStrMac[64] = {0};
_snprintf(DelimitedStrMac, sizeof(DelimitedStrMac)-1, "%02X-%02X-%02X-%02X-%02X-%02X",
(unsigned char)byteMac[0], (unsigned char)byteMac[1], (unsigned char)byteMac[2],
(unsigned char)byteMac[3], (unsigned char)byteMac[4], (unsigned char)byteMac[5] );
return std::string(DelimitedStrMac);
}
//convert byte to unDelimited String
static std::string Byte2UnDelimitedStr(const unsigned char byteMac[6])
{
char unDelimitedStrMac[64] = {0};
_snprintf(unDelimitedStrMac, sizeof(unDelimitedStrMac) - 1, "%02X%02X%02X%02X%02X%02X",
(unsigned char)byteMac[0], (unsigned char)byteMac[1], (unsigned char)byteMac[2],
(unsigned char)byteMac[3], (unsigned char)byteMac[4], (unsigned char)byteMac[5] );
return std::string(unDelimitedStrMac);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
char * initMac = "00-50-56-C0-00-01";
unsigned char mac[6];
MAC_Convertor::DelimitedStr2Byte(initMac, mac);
std::string delimac = MAC_Convertor::Byte2UnDelimitedStr(mac);
cout<<delimac<<endl;
return 0;
}
mac字符串与byte互转工具类
最新推荐文章于 2023-05-15 21:43:29 发布