[英]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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.