指定结构中数组元素的位大小
Specifying bit size of array elements in a struct
现在我有一个看起来像这样的结构:
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) 可能具有更好的性能。
相关文章:
- std::vector的包装器,使数组的结构看起来像结构的数组
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- C++具有动态分配的字符数组的结构
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 复制 C 样式数组和结构
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 删除在结构 c++ 中声明的数组元素
- 指定结构中数组元素的位大小
- std::string 或 char[] 作为大型数组状结构的元素
- 在并集中命名数组元素或结构和数组