数据之间的转换可以使用 System.Convert
Mac地址转换成long长整型
/// <summary>
/// 解析长整形的数据使其转换为macID
/// </summary>
/// <param name="valuetolong">长整形的数据</param>
/// <returns>macID字符串</returns>
public static string Int64ToMacID(long valuetolong)
{
//解析长整形的数据使其转换为MAC;
string valuetostr = valuetolong.ToString("X2");
valuetostr = valuetostr.PadLeft(12, '0');
List<string> listArr = new List<string>();
for (var i = 0; i <= 11; i++)
{
listArr.Add(valuetostr[i].ToString());
if (i < 11 && i % 2 == 1)
{
listArr.Add("-");
}
}
valuetostr = string.Join("", listArr.ToArray());
return valuetostr;
}
/// <summary>
/// 将MAC转为长整形
/// </summary>
/// <param name="macID">macID</param>
/// <returns>长整形</returns>
public static long MacIDToInt64(string macID)
{
long valuetolong = 0;
string v = null;
//将MAC转为长整形:
//测试:string vv = "00-26-2D-F2-5C-28".Replace("-", "");
//string v = macID.Replace("-", "");
if (macID.Contains("-"))
{
v = macID.Replace("-", "");
}
if (long.TryParse(v, System.Globalization.NumberStyles.HexNumber, null, out long macIDToInt64Result))
{
valuetolong = macIDToInt64Result;
}
return valuetolong;
}
private static String keys = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static int exponent = keys.Length;
public static string Long2MACID(long value)
{
string result = string.Empty;
do
{
long index = value % exponent;
result = keys[(int)index] + result;
value = (value - index) / exponent;
}
while (value > 0);
result = result.PadLeft(12, '0');
List<string> listArr = new List<string>();
for (var i = 0; i <= 11; i++)
{
listArr.Add(result[i].ToString());
if (i < 11 && i % 2 == 1)
{
listArr.Add("-");
}
}
return string.Join("", listArr.ToArray());
}
public static long MACID2Long(string value)
{
value = value.Replace("-", "");
long result = 0;
for (int i = 0; i < value.Length; i++)
{
int x = value.Length - i - 1;
result += keys.IndexOf(value[i]) * Pow(exponent, x);
}
return result;
}
/// <summary>
/// 一个数据的N次方
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
private static long Pow(long baseNo, long x)
{
long value = 1;
while (x > 0)
{
value = value * baseNo;
x--;
}
return value;
}