可能的c++ 2位位域数组
C++ 2-bit bitfield arrays possible?
我有一个像这样的2位位域结构体:
struct MyStruct {
unsigned __int32 info0 : 2;
unsigned __int32 info1 : 2;
unsigned __int32 info2 : 2;
...
unsigned __int32 info59 : 2;
};
像这样的另一个可以达到120…有没有一种方法来写和地址他们作为一个数组?
如果你因为任何原因不能使用Paul R的答案,你总是可以使用标准数组的自定义访问器:
static unsigned __int8 infos[30]; // 240 bits allocated
unsigned __int8 getInfo( unsigned short id_num )
{
return (infos[id_num/4] >> ((2*id_num) % 8) ) & 0x3;
}
// setInfo left as an exercise.
(您可能需要检查这里的逻辑,我还没有测试它。)
我将使用代理对象来创建一个临时引用,该引用可用于使用数组语法操作2位项。这可以很容易地修改为处理n位项。
#include <iostream>
class TwoBitArray {
public:
typedef unsigned char byte;
TwoBitArray(unsigned size) : bits(new byte[(size + 3) / 4]) {}
~TwoBitArray() { delete bits; }
class tbproxy {
public:
tbproxy(byte& b, int pos) : b(b), pos(pos) {}
// getter
operator int() const {
return (b >> (pos * 2)) & 3;
}
// setter
tbproxy operator=(int value) {
const byte mask = ~(3 << (pos * 2));
b = (b & mask) | (value << (pos * 2));
return *this;
}
private:
byte& b;
int pos;
};
// create proxy to manipulate object at index
tbproxy operator[](int index) const {
return tbproxy(bits[index/4], index & 3);
}
private:
byte* bits;
};
int main() {
const int size = 20;
TwoBitArray a(size);
for (int i = 0; i < size; ++i)
a[i] = i & 3;
for (int i = 0; i < size; ++i)
std::cout << i << ": " << a[i] << std::endl;
}
相关文章:
- 将浮动的heightmap数组导出为16位原始值
- 对字符数组中的元素执行逐位操作
- 将位字段导出到数组
- 从两个 4x64 位整数数组中获取取模
- 是否可以在 64 位系统中为 11 位系统中的图形创建位邻接数组
- 如何从类函数返回指向类作用域数组的指针?
- MediaFoundation,位图数组到mp4
- 采用OpenCV Mat<doube>并转换为12位值数组。
- 将超过 64 位的数组转换为基数为 10 的字符串
- 如何仅使用数学方法旋转16x16位图数组的内容(无缩放,只需剪切角)
- 大小编译指示打包的位域结构数组
- 将 8 位整数放入 16 位整数数组的最快方法是什么
- 为C++中的每个单元格创建一个只有 2 位的数组
- 表示位在数组中表示的旋转
- scanf 只能将 3 个字符读取到 5 位字符数组中
- 将 8 位值数组重新解释为标准复数值
- 3 位的数组对齐
- 在64位计算机中分配32位整数数组
- 可能的c++ 2位位域数组
- 2bit位域数组对性能和缓存效率的影响