Mac地址转换成long长整型

时间:2022-04-10 02:51:42

Mac地址转换成long长整型

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Test
{
class Program
{
static void Main(string[] args)
{

Console.WriteLine("第一种方式");
//1、将MAC转为长整形:
string vv = "00-26-2D-F2-5C-28".Replace("-", "");
long valuetolong = long.Parse(vv, System.Globalization.NumberStyles.HexNumber);
Console.WriteLine(valuetolong.ToString());
//2、解析长整形的数据使其转换为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());

Console.WriteLine("第二种方式");//这种方式参考https://zhidao.baidu.com/question/1430800143352309939.html
var f1 = Converter.Str2Long("00-26-2D-F2-5C-28");
Console.WriteLine(f1);
Console.WriteLine(f1.ToString("X2"));
var f2 = Converter.Long2Str(f1);
Console.WriteLine(f2);

Console.WriteLine(valuetostr);
Console.Read();

}
private void Form1_Load(object sender, EventArgs e)
{
//此处的 version="1.0" encoding="UTF-8", 在生成的时候一定要有引号,不然会抛出异常
string info = @"<?xml version=""1.0"" encoding=""UTF-8"" ?><ERRORS><ERROR><MSGID>2011323102411&1595489505</MSGID></ERROR><ERROR><MSGID>2011323102411&1396395659</MSGID></ERROR></ERRORS>";

XmlDocument doc = new XmlDocument();
XmlTextReader reader = new XmlTextReader(info, XmlNodeType.Document, null);
while (reader.Read())
{

if (reader.NodeType == XmlNodeType.Element)//判断节点类型为Element
{
//判断节点为MSGID
if (reader.Name == "MSGID")
{
//如果节点为MSGID,继续读下一个节点,即读取MSGID节中电话号码
reader.Read();
//如果节点类型是节点的文本内容
if (XmlNodeType.Text == reader.NodeType)
{
//读取电话号码
// this.richTextBox1.Text += reader.Value + "/r/n";
}
}
}
}

}

}

public class Converter
{
private static String keys = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static int exponent = keys.Length;
public static string Long2Str(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 Str2Long(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;
}
}

}

原文链接:https://zhidao.baidu.com/question/1430800143352309939.html