位封装结构内的数组
我想在位封装结构中有一个数组。我静态地知道数组的大小 (32),并且我希望数组中的每个元素都是单个位。例如,我希望能够这样说:
struct example_s {
// ...
unsigned int flags[32] : 32;
} __attribute__((__packed__));
我已经尝试了一些方法,但 gcc 不会让步。如果能够做到这一点那就太好了,这样我就可以编写干净的代码来迭代打包数组中的元素。有想法吗?
I'd like to have an array inside of a bit-packed struct. I statically know the size of the array (32), and I'd like each element in the array to be a single bit. For example, I would like to be able to say something like:
struct example_s {
// ...
unsigned int flags[32] : 32;
} __attribute__((__packed__));
I've tried a couple things, but gcc won't budge. It would be nice to be able to do this so that I could write clean code that iterated over the elements in the packed array. Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只是将其放入(32 位)int 中,那么您可以使用 for 循环干净地迭代这些位,如下所示:
编写起来并不比数组索引语法难多少。
如果您希望隐藏位旋转以使代码更具可读性,您甚至可以使用函数或宏来访问位 - 例如
GetFlag(bit)
If you simply put it into a (32-bit) int, then you can cleanly iterate over the bits with a for loop like this:
Not much harder to write than an array indexing syntax.
If you wish to hide the bit-twiddling to make the code more readable you could even use a function or macro to access the bits - e.g.
GetFlag(bit)
位域成员元素没有地址,因此即使您可以声明它们的数组,也无法使用它(C 中的所有数组访问都是指针算术和取消引用)。不过,使用较大类型的位来编写自己的位数组很容易;杰森已经解释了基础知识。一般来说,除非有充分的理由,否则您应该避免使用位域。它们带来的麻烦通常超过其价值。
Bitfield member elements do not have addresses, so even if you could declare an array of them, there'd be no way to use it (all array access in C is pointer arithmetic and dereferencing). It's easy to code your own bit array using the bits of a larger type though; Jason has explained the basics. Generally you should avoid using bitfields unless you have a really good reason. They're usually more trouble than they're worth.