5

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.

3 Answers 3

9

here you go

string mac = "b8:27:eb:97:b6:39";
byte[] arr = mac.Split(':').Select(x => Convert.ToByte(x, 16)).ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

Answer of the day! Thank you.
9

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.

7 Comments

Sorry about that. Better?
much :) though I'm not sure that is what the OP wants?
@Toxantron, would be better if you suggest OP to use PhysicalAddress.Parse(str).GetAddressBytes() and then provide the references you have provided.
This will throw an exception as PhysicalAddress.Parse accepts only - as a separator. I've edited the answer with a solution.
After .NET 5, colon character is also a valid separator
|
0

You need to use the Byte.Parse method of the .Net framework.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.