C++ 2-bit bitfield arrays possible?

前端 未结 2 1082
走了就别回头了
走了就别回头了 2020-12-21 09:11

I have a struct of 2-bit bitfields like this:

struct MyStruct {
    unsigned __int32 info0  : 2;
    unsigned __int32 info1  : 2;
    unsigned __int32 info2          


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-21 09:36

    I would use a proxy object to create a temporary reference which could be used to manipulate 2-bit items using array syntax. This could easily be modified to handle n-bit items.

    #include 
    
    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;
    }
    

提交回复
热议问题