在 C# 中表示位数组的最佳方式?
我目前正在 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;
}
如果我们想象每个字段都是一个固定长度的位数组,那么什么是:
- 最通用的
- 最佳实践
将其表示为类的
方法???或者..你会怎么写这个? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于初学者,您可以尝试 BitArray 类。无需在这里重新发明轮子。
如果您担心它占用太多空间/内存,请不要担心。只需将其初始化为正确的大小即可:(
上面将保存 8 位,应占用 1 个字节)
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:
(The above will hold 8 bits and should take up 1 byte)
你走错了路,它不是位向量。该消息以“八位位组”定义,即“字节”。可以与 Marshal.PtrToStructure 一起使用的等效 C# 声明是:
您需要单独处理可变长度选项字段。
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:
You'll need to handle the variable length options field separately.
您确定要对其中一些使用位数组吗?例如,您可以使用 byte 表示 8 位,使用 int 表示 32 位,并使用字节数组表示映射到以 null 结尾的字符串(例如“sname”)的片段。然后您可以使用简单的按位运算符(&、|)来检查/操作这些位。
以下是我关于将 TCP 标头转换为结构的一些帖子,其中还涵盖了字节序等。
http://taylorza.blogspot.com/2010/04/archive-struct-from-binary-data.html
http://taylorza.blogspot.com/2010/ 04/archive-binary-data-from-struct.html
这些已经很旧了,我将它们从我的旧博客迁移出来,这样它们就不会丢失。
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.