Skip to content

Instantly share code, notes, and snippets.

@diegofrata
Created May 24, 2013 10:45
Show Gist options
  • Save diegofrata/5642669 to your computer and use it in GitHub Desktop.
Save diegofrata/5642669 to your computer and use it in GitHub Desktop.
Casting a struct from a byte array using C-style unions and without the unsafe keyword. Yay!
[StructLayout(LayoutKind.Explicit)]
public struct ByteConverter<T> where T : struct
{
#region Private Members
private static int SIZE_OF = Marshal.SizeOf(typeof(T));
[FieldOffset(0)]
private byte[] _bytes;
[FieldOffset(0)]
private T[] _structs;
#endregion
#region Construction and Initialization
public ByteConverter(byte[] bytes)
{
_structs = null;
_bytes = bytes;
}
#endregion
#region Public Properties
public int Length
{
get { return _structs.Length / SIZE_OF; }
}
public T this[int index]
{
get { return _structs[index * SIZE_OF]; }
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment