0

So to start with, it's not a duplicated post as my question is a little bit more special than that.

I know how to convert a string into byte remotely using the File.ReadAllBytes(); command and it works perfectly for remote purpose.

Now I want to achieve the same thing without using the File.ReadAllBytes(); method and do everything inside the code

This is a clear exemple of what i want to achieve exactly :

string myString = @"0x00,0x01,0x02,0x03";

So this is a normal string with 19 character

byte[] myByte = new byte[4] {0x00,0x01,0x02,0x03};

And this is what I want to finish with

Is it possible to convert the string variable into the byte variable dynamically without using the I/O command ?

SharpIt777
  • 27
  • 5

2 Answers2

1

Here's a one liner for you, splits the string on the comma, uses Linq to select each value from the string array and convert it to a byte and finally calls .ToArray to give you the byte array:

string myString = @"0x00,0x01,0x02,0x03";

byte[] myByte = myString.Split(',')
                 .Select(a => Convert.ToByte(a, 16))
                 .ToArray();
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40
0

Something like this?

public byte[] ParseBytes(string bytes)
{
    var splitBytes = bytes.Split(',');
    byte[] result = new byte[splitBytes.Length];
    for (int i = 0; i < splitBytes.Length; i++)
    {
        result[i] = Convert.ToByte(splitBytes[i], 16);
    }
    return result;
}

byte[] myByte = ParseBytes(myString);

Just keep in mind you should add exception handling.

Ekas
  • 150
  • 8
  • or as a lonq one-liner:`var outBytes = bytes.Split(',').Select(b=>Convert.ToByte(b,16)).ToArray();` – pm100 Jul 20 '22 at 22:58