我如何从C中32位序列的立即数中获取值? [英] How I get the value from the Immediate part of a 32 Bit sequence in C?
问题描述
我用C语言构建了一个虚拟机.为此,我有了指令
I built a virtual machine in C. And for this I have the Instruction
pushc <const>
我将命令和值保存在32位中.前8位用于命令,其余部分用于值.
I saved the command and the value in 32 Bit. The First 8 Bit are for the command and the rest for the value.
8位->操作码 24位->立即值
为此,我制作了一个宏
#define PUSHC 1 //1 is for the command value in the Opcode
#define IMMEDIATE(x) ((x) & 0x00FFFFFF)
更新:
**#define SIGN_EXTEND(i) ((i) & 0x00800000 ? (i) | 0xFF000000 : (i))**
然后我加载以在无符号int数组中对此进行测试:
Then I load for testing this in a unsigned int array:
更新:
unsigned int code[] = { (PUSHC << 24 | IMMEDIATE(2)),
(PUSHC << 24 | SIGN_EXTEND(-2)),
...};
稍后在我的代码中,我想获取pushc命令的即时值并将该值推入堆栈...
later in my code I want to get the Immediate value of the pushc command and push this value to a stack...
我从数组中获取每个指令(IR)并构建了我的堆栈.
I get every Instruction (IR) from the array and built my stack.
更新:
void exec(unsigned int IR){
unsigned int opcode = (IR >> 24) & 0xff;
unsigned int imm = (IR & 0xffffff);
switch(opcode){
case PUSHC: {
stack[sp] = imm;
sp = sp + 1;
break;
}
}
...
}
}
推荐答案
只需使用按位AND
屏蔽掉低24位,然后在case
中使用它即可:
Just use a bitwise AND
to mask out the lower 24 bits, then use it in the case
:
const uint8_t opcode = (IR >> 24) & 0xff;
const uint32_t imm = (IR & 0xffffff);
switch(opcode)
{
case PUSHC:
stack[sp] = imm;
break;
}
我转移了操作码的提取内容,以使case
易于阅读.
I shifted around the extraction of the opcode to make the case
easier to read.
这篇关于我如何从C中32位序列的立即数中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!