C# Structure to Byte array conversion

By | December 2, 2018

An utility and some code examples how to automatically convert a struct to byte array and back. This comes very handy when implementing protocols.

Add annotations to your structures, for example:

using System.Runtime.InteropServices;

    public struct Header
        public MessageType messageType;
        public CommandStatus commandStatus;
        public byte receiverAddress;
        public byte senderAddress;

Convert from struct to byte array and vice versa:

byte[] messageBytes = ByteArray.StructureToByteArray(msg);
ReceivedHeader = ByteArray.ByteArrayToStructure<Header>(receivedPacket);

The ByteArray utility is part of Yats.Utilities NuGet package. Source code:

public static T ByteArrayToStructure<T>(byte[] bytes) where T : struct
    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
        T stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
        return stuff;

public static byte[] StructureToByteArray(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);


    return arr;

Leave a Reply

Your email address will not be published.