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
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);
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With