[英]C++ 2-bit bitfield arrays possible?
I have a struct of 2-bit bitfields like this: 我有一个像这样的2位位域结构:
struct MyStruct {
unsigned __int32 info0 : 2;
unsigned __int32 info1 : 2;
unsigned __int32 info2 : 2;
...
unsigned __int32 info59 : 2;
};
And another like this going up to 120... Is there a way to write and address them as an array? 另一个像这样的高达120 ...是否有办法将它们作为数组写入并解决?
If you can't use Paul R's answer for whatever reason, you can always use a custom accessor with a standard array : 如果由于某种原因无法使用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.
(You may need to check the logic here, I haven't tested it.) (您可能需要检查逻辑,我还没有测试过。)
I would use a proxy object to create a temporary reference which could be used to manipulate 2-bit items using array syntax. 我将使用代理对象来创建一个临时引用,可以使用数组语法来操作2位项。 This could easily be modified to handle n-bit items.
这可以很容易地修改为处理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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.