我正在尝试将以下代码转换为C中的联合指令:
typedef struct InstructionTypeI_t {
unsigned long immediate: 16;
unsigned char rt:5; // start a new byte
unsigned char rs : 5;
unsigned char opcode : 6;
} InstructionTypeI_t;
typedef struct InstructionTypeJ_t {
unsigned long address: 26;
unsigned char opcodce: 6;
} InstructionTypeJ_t;
typedef struct InstructionTypeR{
unsigned long funct: 6;
unsigned char shamt:5; // start a new byte
unsigned char rd : 5;
unsigned char rt : 5;
unsigned char rs: 5;
unsigned char opcode: 6;
} InstructionTypeR_t;
/* TODO Task (d) add union Instruction here */
typedef union Instruction{
InstructionTypeI_t i;
InstructionTypeJ_t j;
InstructionTypeR_t r;
}Instruction;
union Instruction instruction
InstructionTypeI_t i;
InstructionTypeJ_t j;
InstructionTypeR_t r;有趣的是这起作用
instruction.i=i;
instruction.j=j;但这会转换错误的值,例如instruction.i.opcode和i.opcode有不同的值。
instruction.i=i;
instruction.j=j;
instruction.r=r;有什么好主意吗?
发布于 2022-03-08 08:13:52
相邻的位字段必须具有相同的基础类型,否则它们不会合并到基础类型的同一个实例中。
例如,通过拥有一个unsigned long位字段,然后是一些unsigned char位字段,您将得到一个只包含该位字段的完整unsigned long变量,而没有其他任何内容。
解决方案是对所有这些位字段使用相同的类型,可能是uint32_t,或者至少是unsigned int。我不使用unsigned long,因为它的非便携大小。
https://stackoverflow.com/questions/71391694
复制相似问题