-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?

Bosiwow
  • 2,025
  • 3
  • 28
  • 46
  • _Any_ effort to solve your problem? – Soner Gönül Dec 04 '15 at 14:11
  • 2
    This question has an answer [here](http://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array). – croxy Dec 04 '15 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. – Jon Skeet Dec 04 '15 at 14:13

1 Answers1

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;
        }
Mariusz
  • 442
  • 5
  • 16
  • But my input is a String [] – Bosiwow Dec 04 '15 at 14:16
  • Use string.Join() method. – Mariusz Dec 04 '15 at 14:18
  • 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?) – Bosiwow Dec 04 '15 at 14:20
  • Why do you have to multiply `str.length` by `sizeof(char)` for the array size? – sab669 Dec 04 '15 at 14:20
  • @Bosiwow Now I understand your question and updated my answer. You can read more [here](https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array). – Mariusz Dec 04 '15 at 14:50
  • Thank you, Right now I've got this: List mac = macadress.Split(':').Select(b => Convert.ToByte(b)).ToList(); But it doesn't work when there is a hex character in the macadress (A,B,C,D,E,F) :( – Bosiwow Dec 04 '15 at 15:36
  • Do you know why the code you provided worked and List mac = macadress.Split(':').Select(b => Convert.ToByte(b)).ToList(); doesn't? – Bosiwow Dec 04 '15 at 15:50