// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Runtime.InteropServices; namespace E { public class Program { private static unsafe byte[] StructureToByteArray(object obj) { int rawsize = Marshal.SizeOf(obj); byte[] arr = new byte[rawsize]; GCHandle handle = GCHandle.Alloc(arr, GCHandleType.Pinned); Marshal.StructureToPtr(obj, handle.AddrOfPinnedObject(), false); handle.Free(); return arr; } public static void Main(string[] args) { int x = 0x12; byte[] b = StructureToByteArray(x); Console.WriteLine(b[0] + " " + b[1] + " " + b[2] + " " + b[3]); } } }