我需要读取十六进制格式的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的位数没有选择...我做错了什么?
答案 0 :(得分:1)
union {
unsigned int address;
unsigned int imm : 16,
rs : 5,
rd : 5,
opcode : 6;
} InstRead;
看看你是否有更好的运气。这取决于您的编译器。
答案 1 :(得分:0)
您的代码适用于我(Windows 7上的gcc 4.8.3)。
您可以使用位操作以更便携的方式提取字段:
imm = address & 0xffff;
rs = address & 0x1f0000 >> 16;
// et cetera