Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 543
Rasmus Bækgaard Avatar asked Apr 06 '16 08:04

Rasmus Bækgaard


2 Answers

here you go

string mac = "b8:27:eb:97:b6:39";
byte[] arr = mac.Split(':').Select(x => Convert.ToByte(x, 16)).ToArray();
like image 190
fubo Avatar answered Nov 01 '22 19:11

fubo


I suggest using PhysicalAddress class instead of doing it yourself.

It has a Parse method:

PhysicalAddress.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 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.

like image 38
Toxantron Avatar answered Nov 01 '22 19:11

Toxantron