指定结构中数组元素的位大小

Specifying bit size of array elements in a struct

本文关键字:数组元素 结构      更新时间:2023-10-16

现在我有一个看起来像这样的结构:

struct Struct {
    uint8_t val1 : 2;
    uint8_t val2 : 2;
    uint8_t val3 : 2;
    uint8_t val4 : 2;
} __attribute__((packed));

有没有办法将所有val变成一个数组?重点不是占用的空间,而是所有值的位置:我需要它们在没有填充的情况下在内存中,并且每个值占用 2 位。拥有数组并不重要,任何其他通过索引简单访问的数据结构都可以,无论是纯 C 还是 C++。读/写性能很重要 - 它应该与现在用于索引访问的简单位操作相同(类似于)。

更新:

我到底想要的可以描述为

struct Struct {
    uint8_t val[4] : 2;
} __attribute__((packed));

不,C 只支持位域作为结构成员,并且不能有它们的数组。我认为你不能做到:

struct twobit {
    uint8_t val : 2;
} __attribute__((packed));

然后做:

struct twobit array[32];

并期望array由 32 个 2 位整数组成,即 8 个字节。我认为,内存中的单个char不能包含不同struct的部分。不过,我现在手边没有段落和经文。

您将不得不自己做,通常使用宏和/或内联函数来执行索引。

你必须手动做现在正在发生的事情:

constexpr uint8_t get_mask(const uint8_t n)
{
  return ~(((uint8_t)0x3)<<(2*n));
}
struct Struct2
{
  uint8_t val;
  inline void set_val(uint8_t v,uint8_t n)
  {
    val = (val&get_mask(n))|(v<<(2*n));
  }
  inline uint8_t get_val(uint8_t n)
  {
    return (val&~get_mask(n))>>(2*n);
  }
  //note, return type only, assignment WONT work.
  inline uint8_t operator[](uint8_t n)
  {
    return get_val(n);
  }
};

请注意,如果使用实际的程序集命令,则可以获得更好的性能。

另请注意,(几乎)无论如何,uint8_t [4] 将具有比这更好的性能,而处理器对齐类型 (uint32_t) 可能具有更好的性能。