Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 791
BananaBuisness Avatar asked Jun 27 '16 16:06

BananaBuisness


2 Answers

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);
}
like image 119
dbush Avatar answered Sep 28 '22 03:09

dbush


Since bitfield layout is compiler dependent, I'm not sure what are you expecting.
The following snippet probably contains undefined behavior, but I guess it's what you are looking for.

Word word;
Command cmd;
cmd.grp = 2;

union
{
    Word word;
    Command cmd;
} u;

u.cmd = cmd;
word = u.word;
like image 29
Dani Avatar answered Sep 28 '22 03:09

Dani