在C#中表示位数组的最佳方法?

时间:2010-04-19 16:59:02

标签: c# syntax construction

我目前正在c#中构建一个DHCPMessage类。

RFC可在此处获取:http://www.faqs.org/rfcs/rfc2131.html

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;
}

如果我们想象每个字段都是固定长度的位数组,那么:

  1. 最通用的
  2. 最佳实践
  3. 将此表示为类的方式???

    或者......你会怎么写这个? :)

3 个答案:

答案 0 :(得分:11)

对于初学者,您可以尝试BitArray课程。无需在这里重新发明轮子。

如果你担心它占用太多空间/内存,请不要。只需将其初始化为正确的大小:

BitArray op = new BitArray(8);

(以上将保持8位,应占用1个字节)

答案 1 :(得分:4)

你这是错误的轨道,它不是一点矢量。消息以“八位字节”定义,更好地称为“字节”。可以与Marshal.PtrToStructure一起使用的等效C#声明是:

    [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;
    }

您需要单独处理可变长度选项字段。

答案 2 :(得分:2)

您确定要为其中一些使用位数组吗?例如,您可以将字节用于8位,int用于32位,字节数组用于映射到空终止字符串的字符串,例如'sname'。然后,您可以使用简单的按位运算符(&,|)来检查/操作位。

以下是我在将TCP标头转换为结构时所做的一些帖子,其中还包括字节顺序等。

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

这些已经很老了,我将它们从旧博客中迁移出来,这样他们就不会迷路了。