简体   繁体   中英

Convert MAC address to byte array in C#

I have a simple MAC address as a string, "b8:27:eb:97:b6:39" , and I would like to get it into a byte array, [184, 39, 235, 151, 182, 57] in C# code.

So I split it up with the following:

var split = str.Split(':');
byte[] arr = new byte[6];

And then I need some sort of for -loop to take each substring turn them into a 16-bit int. I tried Convert.ToInt8(split[i]) , split[i].ToChar(0,2) , (char)split[i] , but I can't figure out how to take to string-characters and let them be a single 8-bit number.

here you go

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

I suggest using PhysicalAdress class instead of doing it yourself.

It has a Parse method:

PhysicalAdress.Parse("b8:27:eb:97:b6:39").GetAdressBytes();

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

But it will fail as the method only accepts - as the byte separator. A simple extension method can help:

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

Then use:

byte[] macBytes = "b8:27:eb:97:b6:39".ToMACBytes();

Edit: Included suggestions.

您需要使用.Net框架的Byte.Parse方法。

byte value = Byte.Parse(split[1], NumberStyles.AllowHexSpecifier);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM