开发者

Best way to represent Bit Arrays in C#?

开发者 https://www.devze.com 2022-12-27 15:42 出处:网络
I am currently building a DHCPMessage class in c#. RFC is available here : http://www.faqs.org/rfcs/rfc2131.html

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 r开发者_C百科epresenting this as a class???

OR.. how would you write this? :)


For starters, you might try the BitArray class. No need to reinvent the wheel here.

If you're worried about it taking up too much space/memory, don't be. Just initialize it to the right size:

BitArray op = new BitArray(8);

(The above will hold 8 bits and should take up 1 byte)


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.


Are you sure you want to be using bit arrays for some of these? For example, you can use byte for 8 bits, int for 32 bits, and byte arrays for pieces that map to null terminated strings like 'sname' for example. Then you can use simple bitwise operators (&, |) to check/manipulate the bits.

Here are some posts I did on converting TCP header to a structure, which also covers endianness etc.

http://taylorza.blogspot.com/2010/04/archive-structure-from-binary-data.html http://taylorza.blogspot.com/2010/04/archive-binary-data-from-structure.html

These are quite old, I migrated them from my old blog just so they do not get lost.

0

精彩评论

暂无评论...
验证码 换一张
取 消