我需要以十六进制格式读取32位地址(例如:0129ef12),并将32位拆分为6-5-5-16个分别代表Opcode-Rd-Rs-Immediate的数据包。
这是我目前为止写的:
typedef unsigned char u8;
typedef unsigned short u16;
union {
unsigned int address;
struct {
u16 imm : 16;
u8 rs : 5;
u8 rd : 5;
u8 opcode : 6;
} i;
} InstRead;
InstRead.address = 0x0129ef12;
cout << hex << int(InstRead.i.opcode) << "n";
cout << hex << int(InstRead.i.rs) << "n";
cout << hex << int(InstRead.i.rd) << "n";
cout << hex << int(InstRead.i.imm) << "n";
然而,这并没有给出正确的输出…也就是说,比特不是由我指定的长度6-5-5-16选择的…我做错了什么?
union {
unsigned int address;
unsigned int imm : 16,
rs : 5,
rd : 5,
opcode : 6;
} InstRead;
看看你是否有更好的运气。这取决于你的编译器
你的代码为我工作(gcc 4.8.3在Windows 7上)。
您可以使用位操作以更可移植的方式提取字段:
imm = address & 0xffff;
rs = address & 0x1f0000 >> 16;
// et cetera