1

I need to create byte array for testing. I implemented my own solution but not sure if it is optimal. Here it is:

byte counter = 0;
Func<int, byte[]> createByteArray = size =>
{
    var array = new byte[size];
    for (int index = 0; index < size; index++)
    {
        array[index] = counter++;

        if (counter == byte.MaxValue)
        {
            counter = 0;
        }
    }
    return array;
};

Are there any ways to simplify this?

3
  • 1
    Why are you declaring counter outside of the function? Are you aware of potential issues with variable closure? Commented Aug 20, 2015 at 14:40
  • so you wish to create an array of size x and fill it with numbers which increment? does the array need to contain incremental numbers? Commented Aug 20, 2015 at 14:42
  • @Mark yes, I'd like to have an array with incremental numbers Commented Aug 20, 2015 at 14:46

3 Answers 3

4

I am not sure this is better or not, but shorter.

Func<int, byte[]> createByteArray = size => Enumerable.Range(0, size)
                                            .Select(i => (byte)(i % 256))
                                            .ToArray();
Sign up to request clarification or add additional context in comments.

Comments

1

Since it's for testing, you can create a complete random buffer using Random.NextBytes(...).

If not, you don't need the branch:

Func<int, byte[]> createByteArray = size =>
{
    var array = new byte[size];
    for (int index = 0; index < size; index++)
    {
        array[index] = (byte)(index & 0xFF);
    }
    return array;
};

Comments

0

You got C#! Use it!

byte counter = 0;
Func<int, byte[]> createByteArray = size =>
{
    var array = new byte[size];
    for (int index = 0; index < size; index++)
    {
        unchecked 
        {
            array[index] = counter++;
        }
    }
    return array;
};

Not sure why you got the counter outside. But If you like it this way...

Use the unchecked block to allow number overflowing in there. That will limit your value to what ever is possible in the byte range automatically.

I don't know how big the arrays are you are generating. If the generation speed is a issue and the arrays are very large you could only fill the values 0 to 255 by hand and after that is done start to copy the chucks into the remaining array. See Array.ConstrainedCopy for this. But this is only relevant if the array generation is too slow and the arrays are very large (n-times the range of Byte)

2 Comments

Actually a smart solution using unchecked, thats something you forget about sometimes.
I use VB.net so I never forget about this function. I am jealous because I don't have it. :| ;)

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.