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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With