任何人都可以告诉是否可以将一种类型的位域分配给其他类型?支持C90编译器。
这里是位域的结构:
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;
这是主程序:
int main(int argc, const char * argv[]){
Word word;
Command cmd;
cmd.grp = 2;
word = cmd;
}
假设我这里有这 15 位:
我们按以下顺序排列它们:
命令:
Dumy | grp | opcode | srcar | destar | ERA
0 0 0 0 1 0 0 0 1 10 0 0 0 0
单词:
| word |
000000000000000
目标是单词等于整个命令(word = command
)所以我们看起来像这样:
| word |
000010001100000
最佳答案
你可能想要的是 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);
}
关于c - 是否可以将一种类型的位域转换为具有相同总位数的另一种类型的位域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38058915/