在C#中将MAC地址转换为字节数组

Ras*_*ard 5 c# bytearray type-conversion

我有一个简单的MAC地址作为字符串,"b8:27:eb:97:b6:39"我想把它变成一个字节数组,[184, 39, 235, 151, 182, 57]用C#代码.

所以我将其拆分为以下内容:

var split = str.Split(':');
byte[] arr = new byte[6];
Run Code Online (Sandbox Code Playgroud)

然后我需要某种for-loop来将每个子字符串转换为16位int.我试过Convert.ToInt8(split[i]),split[i].ToChar(0,2),(char)split[i],但我无法弄清楚如何采取串字符,让他们成为一个8位数字.

fub*_*ubo 8

干得好

string mac = "b8:27:eb:97:b6:39";
byte[] arr = mac.Split(':').Select(x => Convert.ToByte(x, 16)).ToArray();
Run Code Online (Sandbox Code Playgroud)


Tox*_*ron 6

我建议使用 PhysicalAdress 类而不是自己做。

它有一个 Parse 方法:

PhysicalAdress.Parse("b8:27:eb:97:b6:39").GetAdressBytes();
Run Code Online (Sandbox Code Playgroud)

参考:https : //msdn.microsoft.com/library/system.net.networkinformation.physicaladdress.parse(v=vs.110).aspx

但它会失败,因为该方法只接受-作为字节分隔符。一个简单的扩展方法可以帮助:

    public static byte[] ToMACBytes(this string mac) {
        if (mac.IndexOf(':') > 0)
            mac = mac.Replace(':', '-');
        return PhysicalAddress.Parse(mac).GetAddressBytes();
    }
Run Code Online (Sandbox Code Playgroud)

然后使用:

byte[] macBytes = "b8:27:eb:97:b6:39".ToMACBytes();
Run Code Online (Sandbox Code Playgroud)

编辑:包括建议。