我们经常需要一些bool数组来做一堆标识,其实一个bool占1bit就够了
所以我设计了MDFlag类,代码很简单,但是很实用。所以当作个基本类型使用
#pragma pack(push)
#pragma pack(1)
template <uint16 Leng, bool defV = false>
struct MDFlag
{
static constexpr uint8 OneTrueBit[8] = { 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80 };
static constexpr uint8 OneFalseBit[8] = { 0xFE, 0xFD, 0xFB, 0xF7, 0xEF, 0xDF, 0xBF, 0x7F };
int8 mPtr[Leng];
public:
MDFlag() {
fill(defV);
}
inline MDFlag& operator =(int v) {
if (Leng <= sizeof(v)) {
memcpy(mPtr,&v, Leng);
}
else {
memcpy(mPtr, &v, sizeof(v));
if (v) {
memset(mPtr + sizeof(v), 0xFF, sizeof(mPtr) - sizeof(v));
}
else {
memset(mPtr + sizeof(v), 0, sizeof(mPtr) - sizeof(v));
}
}
return *this;
}
inline operator int() {
int v = 0;
if (Leng <= sizeof(v)) {
memcpy(&v, mPtr, Leng);
}
else {
memcpy(&v, mPtr, sizeof(v));
}
return v;
}
inline void fill(bool v) {
if (v) {
memset(mPtr, 0xFF, sizeof(mPtr));
}
else {
memset(mPtr, 0, sizeof(mPtr));
}
}
inline bool get(uint16 pos) {
auto n = pos / 8;
if (n >= Leng) {
return defV;
}
auto left = pos % 8;
return (mPtr[n] & OneTrueBit[left]) != 0;
return true;
}
inline void set(uint16 pos, bool v) {
auto n = pos / 8;
if (n >= Leng) {
return;
}
auto left = pos % 8;
if (v) {
mPtr[n] |= OneTrueBit[left];
}
else {
mPtr[n] &= OneFalseBit[left];
}
}
};
#pragma pack(pop)
我是直接在c#版本里抄过来的,其实我有个c#版本的vm!!!