Search code examples
c#syntaxconstruction

Best way to represent Bit Arrays in C#?


I am currently building a DHCPMessage class in c#.

RFC is available here : http://www.faqs.org/rfcs/rfc2131.html

Pseudo

public object DHCPMessage
{
    bool[8] op;
    bool[8] htype;
    bool[8] hlen;
    bool[8] hops;
    bool[32] xid;
    bool[16] secs;
    bool[16] flags;
    bool[32] ciaddr;
    bool[32] yiaddr;
    bool[32] siaddr;
    bool[32] giaddr;
    bool[128] chaddr;
    bool[512] sname;
    bool[1024] file;
    bool[] options;
}

If we imagine that each field is a fixed length bit array, what is :

  1. The most versitile
  2. Best practice

way of representing this as a class???

OR.. how would you write this? :)


Solution

  • You are on the wrong track with this, it isn't a bit vector. The message is defined in "octets", better known as "bytes". An equivalent C# declaration that you can use with Marshal.PtrToStructure is:

        [StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
        struct DHCPMessage {
            public byte op;
            public byte htype;
            public byte hlen;
            public byte hops;
            public uint xid;
            public ushort secs;
            public ushort flags;
            public uint ciaddr;
            public uint yiaddr;
            public uint siaddr;
            public uint giaddr;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
            public byte[] chaddr;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst=64)]
            public string sname;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
            public string file;
        }
    

    You'll need to handle the variable length options field separately.