-3

I'm kindof a C# noob and I want to create a byte[] from a String[].

Here is an example:

string[] macString = new string[]{"AA","11","02","BB","A5","AA"}; 

And I want the following output:

byte[] mac = new byte[] { 0xAA, 0x11, 0x02, 0xBB, 0xA5, 0xAA };

Can somebody help me with this?

3
  • Any effort to solve your problem? Commented Dec 4, 2015 at 14:11
  • 2
    This question has an answer here. Commented Dec 4, 2015 at 14:11
  • Or at least - that provides the relevant bits. You'll need to reassemble them a little to fit the fact that you've got an array rather than a single string, but there are various different ways of handling that. Commented Dec 4, 2015 at 14:13

1 Answer 1

0

You must convert hex string to byte:

        public static byte[] StringToByteArray(string[] hexs)
        {
            var hex = string.Join(string.Empty, hexs);

            byte[] array = Enumerable.Range(0, hex.Length)
                .Where(x => x % 2 == 0)
                .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                .ToArray();

            return array;
        }
Sign up to request clarification or add additional context in comments.

7 Comments

But my input is a String []
Use string.Join() method.
If I got the string "AA1102BBA5AA", will the output be: byte[] { 0xAA, 0x11, 0x02, 0xBB, 0xA5, 0xAA } ? (How does it know if it has to split every two characters?)
Why do you have to multiply str.length by sizeof(char) for the array size?
@Bosiwow Now I understand your question and updated my answer. You can read more here.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.