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 ?

3
  • @RyanWilson, unfortunately it doesn't because it will convert every char into bytes even the "," ones Commented Jul 20, 2022 at 22:38
  • 1
    Then split and parse... Where is the problem? Commented Jul 20, 2022 at 22:38
  • @Selvin I wish it was as easy as that, it has to be done the way i described for my project to work, i can't just copy/paste it like that Commented Jul 20, 2022 at 22:40

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

or as a lonq one-liner:var outBytes = bytes.Split(',').Select(b=>Convert.ToByte(b,16)).ToArray();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.