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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Vivekananda
    New Member
    • Nov 2008
    • 3

    #1

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

    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
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    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 ?

    Comment

    • Vivekananda
      New Member
      • Nov 2008
      • 3

      #3
      Thanks for the reply.

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

      Code snippet:
      Code:
      abyteArray0 = abyteArray[0]; //source
      byte[] NewArray = null; //dest
      
                  for (int i = 0; i < abyteArray0.Length ; i++)
                  {
                      if ((i % 2 == 0))
                      {
                          //NewArray[i] = abyteArray0[i];
                          Array.Copy(abyteArray0, i, NewArray, i, 1);
                      }
                      i = i + 1;
      
                  }

      Comment

      • Curtis Rutland
        Recognized Expert Specialist
        • Apr 2008
        • 3264

        #4
        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

        Comment

        • Plater
          Recognized Expert Expert
          • Apr 2007
          • 7872

          #5
          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.Lengt h/2)+(oldarray.Le ngth%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.

          Comment

          • Vivekananda
            New Member
            • Nov 2008
            • 3

            #6
            Thanks very much. Got it!

            Comment

            Working...