Home > OS >  Converting string into byte dynamically C#
Converting string into byte dynamically C#

Time:07-21

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 ?

CodePudding user response:

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.

CodePudding user response:

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();
  •  Tags:  
  • c#
  • Related