C ++ pointer to a specific bit size

My question is to point to chunks of memory with an odd size.

Let's say I have structone declared like this:

typedef struct{
   int32 val1  : 29; 
   int32 val2  : 26;
   char  val3;
}MyStruct;

Suppose that declaring certain bit fields in a structure is desirable (why we will use bit fields is not a question).

If I wanted to declare a pointer pointing to one of these fields, I could try something like this:

MyStruct test;
int32 *myPtr = &(test.val1);

Except that this leads to an error, "receiving a bit field address is not allowed."

Assuming we want, is there a way to point to these fields this way? I know that C ++ is likely to put the fields in the next byte (which will be 32 bits in this case).

+5
source share
3 answers

++ 1 . , , .

++ 03 9.6 -:
3:

... - & , .....

+11

, , " ".

. . [class.bit] 9.6/3:

- , .

( CHAR_BIT , CHAR_BIT 8) - , .

, , ?

. , struct. C; . C FAQ 2.26:

- , (, ).

, std::bitset boost::dynamic_bitset.

+6

. , , . :

class BitFieldPointer
{
    unsigned* myData;
    unsigned  myMask;
    unsigned  myShift;

    class DereferenceProxy
    {
        BitFieldPointer const* myOwner;
    public:
        DereferenceProxy(BitFieldPointer const* owner) : myOwner( owner ) {} operator unsigned() const
        {
            return (*myOwner->myData && myOwner->myMask) >> myOwner->myShift;
        }

        void operator=( unsigned new_value ) const
        {
            *myData = (*myOwner->myData && ~myOwner->myMask) |
                    ((new_value << myOwner->myShift) && myOwner->myMask);
        }
    };
public:
    //  ...
    DereferenceProxy operator*() const
    {
        return DereferenceProxy(this);
    }
};

( . , , const - .)

0

All Articles