I need to fill a byte[]
with a single non-zero value. How can I do this in C# without looping through each byte
in the array?
Update: The comments seem to have split this into two questions -
memset
I totally agree that using a simple loop works just fine, as Eric and others have pointed out. The point of the question was to see if I could learn something new about C# :) I think Juliet's method for a Parallel operation should be even faster than a simple loop.
Benchmarks: Thanks to Mikael Svenson: http://techmikael.blogspot.com/2009/12/filling-array-with-default-value.html
It turns out the simple for
loop is the way to go unless you want to use unsafe code.
Apologies for not being clearer in my original post. Eric and Mark are both correct in their comments; need to have more focused questions for sure. Thanks for everyone's suggestions and responses.
There isn't a standard function for this - you will just need to call memcpy() in a loop: my_stuff *my_array = malloc(MAX * sizeof(my_stuff)); my_stuff tmp; size_t i; tmp.
C library function - memset() The C library function void *memset(void *str, int c, size_t n) copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str.
memset sets the bytes in a block of memory to a specific value. malloc allocates a block of memory.
Description. The memset() function sets the first count bytes of dest to the value c. The value of c is converted to an unsigned character.
You could use Enumerable.Repeat
:
byte[] a = Enumerable.Repeat((byte)10, 100).ToArray();
The first parameter is the element you want repeated, and the second parameter is the number of times to repeat it.
This is OK for small arrays but you should use the looping method if you are dealing with very large arrays and performance is a concern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With