1

I'm trying to fill two byte[] form a string.

string xpto = "{ 0, 0, 5 },{  1, 255, 1 }";

It could be done by splitting and parsing. But I want to avoid lots of code, and at same time learn a clever way of doing this... using C#!

Thanks for any help! :)

2
  • You can use the BitConverter class to do this. Commented Dec 18, 2013 at 18:29
  • 1
    For me is not so clear how do you expect the conversion to work for the given example Commented Dec 18, 2013 at 18:42

4 Answers 4

1
var arrays = Regex.Matches(xpto, @"{([^}]+)}")
                  .Cast<Match>()
                  .Select(m => m.Groups[1].Value // take group value " 0, 0, 5 "
                                .Split(',') // split into three strings
                                .Select(s => Byte.Parse(s.Trim())) // parse each
                                .ToArray()); // convert to byte array
Sign up to request clarification or add additional context in comments.

Comments

1

I think this would be an easy way to do that :

string xpto = "{ 0, 0, 5 },{  1, 255, 1 }";
var convertedBytes = Regex.Split(xpto, @"\D+")
    .ToList()
    .Where(x => x!="")
    .Select(x => Convert.ToByte(x))
    .ToList();

Comments

0

You can split by "},{", then split each one by "," and remove what's not necessary.

    string xpto = "{ 0, 0, 5 },{  1, 255, 1 }";
    List<byte[]> listOfByteArrs = new List<byte[]>();

    string[] byteArrSplitter = Regex.Split(xpto, "},{");

    foreach (string byteArrString in byteArrSplitter)
    {
        string[] byteSplitter = Regex.Split(byteArrString, ",");
        byte[] byteHolder = new byte[byteSplitter.Count()];

        for (int i = 0; i < byteSplitter.Count(); i++)
        {
            byteHolder[i] = Convert.ToByte(Regex.Replace(byteSplitter[i].ToString(), @"\{|\}|\s", ""));
        }
        listOfByteArrs.Add(byteHolder);
    }

The code is pretty straight forward, split the string into "byte arrays", then split by "," to get each value, clean it up and asign it to a new byte. Then add it to a list, if you want your byte[] listed.

1 Comment

I actually tested its execution time, and surprisingly my method counted 1354 ticks, while Plexus' counted 14251 ticks. Thought it would be the other way around.
0

Here is a parser-based solution (for fun). It should be faster (about 10 ticks on an i7) than the other answers though, but not as maintainable.

var p = new Parser();
byte[][] data = p.Parse("{ 0, 0, 5 },{  1, 255, 1 }");


class Parser
{
    char c;
    int i;
    string data;

    private bool next()
    {
        if (i == data.Length) { c = (char)0; return false; }
        else { c = data[i++]; return true; }
    }

    public byte[][] Parse(string data)
    {
        this.data = data;
        if (data.Length == 0) return null;
        i = 0;
        List<List<byte>> result = new List<List<byte>>();
        List<byte> currentList = new List<byte>();
        while (next())
        {
            switch (c)
            {
                case '{': currentList = new List<byte>(); break;
                case '}': result.Add(currentList);        break;
                default : ParseByte(currentList);         break;
            }
        }
        return result.Select(l => l.ToArray()).ToArray();
    }

    private void ParseByte(List<byte> currentList)
    {
        if (!char.IsDigit(c)) return;
        byte currentByte = 0;
        while (char.IsDigit(c))
        {
            currentByte *= 10;
            currentByte += (byte)(c - '0');
            next();
        }
        currentList.Add(currentByte);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.