title: C# unsafe value type array to byte array conversions
body: <p>I use an extension method to convert float arrays into byte arrays:</p>
  
  <pre><code>public static unsafe byte[] ToByteArray(this float[] floatArray, int count)
  {
      int arrayLength = floatArray.Length &gt; count ? count : floatArray.Length;
      byte[] byteArray = new byte[4 * arrayLength];
      fixed (float* floatPointer = floatArray)
      {
          fixed (byte* bytePointer = byteArray)
          {
              float* read = floatPointer;
              float* write = (float*)bytePointer;
              for (int i = 0; i &lt; arrayLength; i++)
              {
                  *write++ = *read++;
              }
          }
      }
      return byteArray;
  }
  </code></pre>
  
  <p>I understand that an array is a pointer to memory associated with information on the type and number of elements. Also, it seems to me that there is no way of doing a conversion from and to a byte array without copying the data as above.</p>
  
  <p>Have I understood this? Would it even be impossible to write IL to create an array from a pointer, type and length without copying data?</p>
  
  <p><strong>EDIT:</strong> Thanks for the answers, I learned some fundamentals and got to try out new tricks!</p>
  
  <p>After initially accepting Davy Landman's answer I found out that while his brilliant StructLayout hack does convert byte arrays into float arrays, it does not work the other way around. To demonstrate:</p>
  
  <pre><code>[StructLayout(LayoutKind.Explicit)]
  struct UnionArray
  {
      [FieldOffset(0)]
      public Byte[] Bytes;
  
      [FieldOffset(0)]
      public float[] Floats;
  }
  
  static void Main(string[] args)
  {
      // From bytes to floats - works
      byte[] bytes = { 0, 1, 2, 4, 8, 16, 32, 64 };
      UnionArray arry = new UnionArray { Bytes = bytes };
      for (int i = 0; i &lt; arry.Bytes.Length / 4; i++)
          Console.WriteLine(arry.Floats[i]);
  
      // From floats to bytes - index out of range
      float[] floats = { 0.1f, 0.2f, 0.3f };
      arry = new UnionArray { Floats = floats };
      for (int i = 0; i &lt; arry.Floats.Length * 4; i++)
          Console.WriteLine(arry.Bytes[i]);
  }
  </code></pre>
  
  <p>It seems that the CLR sees both arrays as having the same length. If the struct is created from float data, the byte array's length is just too short. </p>