You'll need the following two methods to perform conversions to and from byte arrays. I am assuming this is all Little Endian.
/// <summary>
/// Converts the supplied object to a byte array.
/// </summary>
public static byte[] ToByteArray(object obj)
{
int len = Marshal.SizeOf(obj);
byte[] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, len);
Marshal.FreeHGlobal(ptr);
return arr;
}
/// <summary>
/// Maps the supplied byte array onto a structure of the specified type.
/// </summary>
public static T ToStructure<T>(byte[] byteArray)
{
GCHandle h = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
T result = (T)Marshal.PtrToStructure(h.AddrOfPinnedObject(), typeof(T));
h.Free();
return result;
}
Now you just need a structure that will hold your data. It will look something like this:
[StructLayout(LayoutKind.Explicit)]
public struct PacketHeader
{
public UInt32 HEADER;
public UInt16 OP;
}
And then all you have to do is populate an instance of PacketHeader with data, and convert it to a byte array like this:
var packetHeader = new PacketHeader
{
HEADER=2,
OP=3
};
var bytes = ToByteArray(packetHeader);
To reverse the process:
var packetHeader p FromByteArray<PacketHeader>(bytes);