Connecting Tech Pros Worldwide Help | Site Map

C# - How do I copy alternate elements from one byte array to another

Newbie
 
Join Date: Nov 2008
Posts: 3
#1: Nov 4 '08
I have a byte array. I need to copy alternate elements 0,2nd,4th ,6th ,8th elements ......and so on from the source byte array to new destination array.

How do I do that in C#?
Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,158
#2: Nov 4 '08

re: C# - How do I copy alternate elements from one byte array to another


Use a for loop and make it count by 2?
Or use a regular for loop and only take the ones were loopiterator%2==0 ?
Newbie
 
Join Date: Nov 2008
Posts: 3
#3: Nov 4 '08

re: C# - How do I copy alternate elements from one byte array to another


Thanks for the reply.

I'm doing that. But I'm getting error saying that "{"Value cannot be null.\r\nParameter name: dest"}"

Code snippet:
Expand|Select|Wrap|Line Numbers
  1. abyteArray0 = abyteArray[0]; //source
  2. byte[] NewArray = null; //dest
  3.  
  4.             for (int i = 0; i < abyteArray0.Length ; i++)
  5.             {
  6.                 if ((i % 2 == 0))
  7.                 {
  8.                     //NewArray[i] = abyteArray0[i];
  9.                     Array.Copy(abyteArray0, i, NewArray, i, 1);
  10.                 }
  11.                 i = i + 1;
  12.  
  13.             }
insertAlias's Avatar
Forum Leader
 
Join Date: Apr 2008
Location: San Antonio, TX (USA)
Posts: 2,608
#4: Nov 4 '08

re: C# - How do I copy alternate elements from one byte array to another


Please enclose your posted code in [CODE] [/CODE] tags (See How to Ask a Question).

This makes it easier for our Experts to read and understand it. Failing to do so creates extra work for the moderators, thus wasting resources, otherwise available to answer the members' questions.

Please use [CODE] [/CODE] tags in future.

MODERATOR
Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,158
#5: Nov 4 '08

re: C# - How do I copy alternate elements from one byte array to another


Well, to address your error, you never set your desitnation array to an instance of an array, you leave it at null. You cannot use a null object as an instance.

Secondly however, your loop/copy logic is a bit flawed (which you will see when you are able to step through it)

To get a newarray of the correct size, consider this:
byte[] NewArray = new byte[(oldarray.Length/2)+(oldarray.Length%2)];

if source array had 5 elements (.Length=5) 0 1 2 3 4
You want 0 2 4, which is an array with 3 elements (.Length=3)
oldarray.Length/2 will be 2 and oldarry.Length%2 =1, so 2+1=3, the number of elements you need.
Newbie
 
Join Date: Nov 2008
Posts: 3
#6: Nov 4 '08

re: C# - How do I copy alternate elements from one byte array to another


Thanks very much. Got it!
Reply