判断两个MAC地址是否相邻
问题描述
有两个MAC地址,如”FE:FF:FE:AB:AB:FF” 和”FE:FF:FE:AB:AB:FE”, 它们之间相差1,则这两个地址是相邻的。如”FE:FF:FE:AB:AB:FF”和”FE:FF:FE:AB:AB:F0”, 则它们是不相邻的。
注意:”FE:FF:FE:AB:AB:FF”和”FE:FF:FE:AB:AC:00”也是相邻的,你的程序要能够认识到这一点。
解题思路
MAC地址是48位的,把它转换成64位的整数就可以解决这个问题。
代码
bool IsHex(char c)
{
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
int HexToInt(char c)
{
if (c >= '0' && c <= '9')
{
return (c - '0');
}
if (c >= 'a' && c <= 'f')
{
return (10 + c - 'a');
}
if (c >= 'A' && c <= 'F')
{
return (10 + c - 'A');
}
return -1;
}
bool IsLegalMacAddr(const char *macStr)
{
const char *p;
char c;
int comCnt;
bool ret;
int digitCnt;
comCnt = 0;
digitCnt = 0;
ret = true;
if (macStr == NULL)
return ret;
p = macStr;
// The first char must be '0'-'9' || 'a-f' || 'A-F'
if (IsHex(*p))
{
while ((c = *p++) != '\0')
{
if (!IsHex(c))
{
if (c == ':')
{
digitCnt = 0;
comCnt++;
}
else
{
ret = false;
break;
}
}
else
{
digitCnt++;
if (digitCnt > 2)
{
ret = false;
break;
}
}
}
}
if (comCnt != 5)
{
// The count of ':' must be 5
ret = false;
}
if (digitCnt == 0)
{
// The last charactor can't be ':'
ret = false;
}
return ret;
}
__int64 MacAddrToInt64(const char *macStr)
{
__int64 ret = 0;
char c;
const char *p = macStr;
if (!IsLegalMacAddr(macStr))
{
return -1;
}
while ((c = *p++) != '\0')
{
if (IsHex(c))
{
ret = ret * 16 + (__int64)(HexToInt(c));
}
else if (c == ':')
{
continue;
}
else
{
ret = -1;
break;
}
}
return ret;
}
bool CheckAdjMacAddr(const char *macAddr1, const char *macAddr2)
{
if ((!IsLegalMacAddr(macAddr1)) || (!IsLegalMacAddr(macAddr2)))
{
return false;
}
return abs(MacAddrToInt64(macAddr1) - MacAddrToInt64(macAddr2)) == 1;
}
int main()
{
char *mac1 = "FE:FF:FE:AB:AB:FF";
char *mac2 = "FE:FF:FE:AB:CD:AB";
char *mac3 = "FE:FF:FE:AB:AC:00";
printf("%d\n", CheckAdjMacAddr(mac1, mac2));
printf("%d\n", CheckAdjMacAddr(mac1, mac3));
return 0;
}