cstructbit-fieldsc89

Is it possible to cast one type of bitfield to another type of bitfield with the same total number of bits?


Anyone could tell if its possible to assign one type of bitfield to other type? With support of C90 compiler.

Here is the structs of the bitfields:

typedef struct{
    unsigned int ERA:2;
    unsigned int destar:2;
    unsigned int srcar:2;
    unsigned int opcode:4;
    unsigned int grp:2;
    unsigned int dumy:3;
} Command;
typedef struct{
    unsigned int cell:15;
} Word;

Here is the main program:

int main(int argc, const char * argv[]){
    Word word;
    Command cmd;
    cmd.grp = 2;
    word = cmd;
}

Let's say I have these 15 bits here:

We arrange them in this order:

Command:

Dumy |    grp | opcode |   srcar | destar | ERA
 0 0 0   0 1    0 0 0 1     10      0 0     0 0

Word:

 |          word              |
000000000000000

The goal is that word will be equal to the whole Command (word = command)so we'd will look like that:

|           word            |
000010001100000

Solution

  • What you probably want here is a union:

    typedef union {
        struct {
            //unsigned int:1;        // padding bit either here...
            unsigned int ERA:2;
            unsigned int destar:2;
            unsigned int srcar:2;
            unsigned int opcode:4;
            unsigned int grp:2;
            unsigned int dumy:3;
            //unsigned int:1;         // ...or here, depending on how you want to read it
        } cmd;
        uint16_t word;
    } Cmd;
    
    int main(int argc, const char * argv[]){
        Cmd cmd;
        cmd.cmd.grp = 2;
        printf("word=%u\n", cmd.word);
    }