views:

664

answers:

4

i want to divide byte array into 3 parts in C#..

my array has foll values-->

0000000000 65535 f
0000000014 00000 n
0000000074 00000 n

each entry is 20 bytes long.i want to store it in struct variable

myStruct[i].offset , myStruct[i].genno , myStruct[i].flag

where offset , genno, flag is not an array its an ulong , ulong, char type ..i have array of struct.

+3  A: 

Use the Array.Copy method to copy part of an array into another array:

myStruct.flag = new byte[20];
Array.Copy(theArray, 40, myStruct.flag, 0, 20);

However, you shuld use a class rather than a structure. A structure that contains mutable reference types is unintuitive and you can easily make mistakes when you use it.

Guffa
+2  A: 

You could use the BlockCopy method to copy data from one byte array to another:

byte[] array = ...

byte[] part1 = new byte[20];
Buffer.BlockCopy(array, 0, part1, 0, 20);

byte[] part2 = new byte[20];
Buffer.BlockCopy(array, 20, part2, 0, 20);

byte[] part3 = new byte[20];
Buffer.BlockCopy(array, 40, part3, 0, 20);

Of course in this example the initial array must be at least 60 bytes long or it will throw an exception.

Darin Dimitrov
Shouldn't that be `Buffer.BlockCopy(array, 40, part3, 0, 20);` on the last line?
Daniel May
@Daniel, you are correct, I've updated my post.
Darin Dimitrov
A: 

Is this what you're after ?

  public struct MyStruct
  {
      private byte[20] off;
      private byte[20] gen;
      private byte[20] flg;
      public byte[20] Offset
      {
         get { return off; }
         set { off = value; }
      }
      public byte[20] Genno
      {
         get { return gen; }
         set { gen = value; }
      }
      public byte[20] Flag
      {
         get { return flg; }
         set { flg= value; }
      }
      public MyStruct(byte[60] inputBytes)
      {
          Array.Copy(inputBytes, 0, off, 0, 19);
          Array.Copy(inputBytes, 20, gen, 0, 19);
          Array.Copy(inputBytes, 40, flg, 0, 19);
      }
   }
Charles Bretana
A: 

If you define your struct class using a StructLayout/FieldOffset, you can practically transform your data directly to an array of your struct class using a single copy operation:

[StructLayout(LayoutKind.Explicit, Size=20)]
class MyStruct
{
   [FieldOffset(0)]public ushort offset; 
   [FieldOffset(2)]public ushort genno;
   [FieldOffset(4)]public char flag;

}

Then a MyStruct[] array will byte-to-byte map directly over your data.

Radu094