How to convert a structure to a byte array in C#?

前端 未结 14 839
难免孤独
难免孤独 2020-11-22 09:59

How do I convert a structure to a byte array in C#?

I have defined a structure like this:

public struct CIFSPacket
{
    public uint protocolIdentifi         


        
14条回答
  •  难免孤独
    2020-11-22 10:18

    I know this is really late, but with C# 7.3 you can do this for unmanaged structs or anything else that's unmanged (int, bool etc...):

    public static unsafe byte[] ConvertToBytes(T value) where T : unmanaged {
            byte* pointer = (byte*)&value;
    
            byte[] bytes = new byte[sizeof(T)];
            for (int i = 0; i < sizeof(T); i++) {
                bytes[i] = pointer[i];
            }
    
            return bytes;
        }
    

    Then use like this:

    struct MyStruct {
            public int Value1;
            public int Value2;
            //.. blah blah blah
        }
    
        byte[] bytes = ConvertToBytes(new MyStruct());
    

提交回复
热议问题