我正在开发虚拟机,并且我的推送指令有问题。它推送显式值而不是引用寄存器中的值,例如:
0x0064 //this line puts hexadecimal for 100 into register 0
0x4000 //this is the line i question this will literally put
//0 into the stack as an explicit value. i want it to
//put what is in register 0(line 1) into the stack
我在下面列出了我的VM的c源代码:
#include <stdio.h>
#include <stdlib.h>
#define NUM_REGS 16
unsigned short regs[ NUM_REGS ];
unsigned program[] = { 0x10C8, 0x1164, 0x2201, 0x4200, 0x0000 };
unsigned stack[10];
int i = 0;
/* program counter */
int pc = 0;
/* fetch the next word from the program */
int fetch()
{
return program[ pc++ ];
}
/* instruction fields */
int instrNum = 0;
int reg1 = 0;
int reg2 = 0;
int reg3 = 0;
int imm = 0;
/* decode a word */
void decode( int instr )
{
instrNum = (instr & 0xF000) >> 12;
reg1 = (instr & 0xF00) >> 8;
reg2 = (instr & 0xF0 ) >> 4;
reg3 = (instr & 0xF );
imm = (instr & 0xFF );
}
/* the VM runs until this flag becomes 0 */
int running = 1;
/* push element onto stack */
void push( reg )
{
int a;
for(a = 10; a <= 10; i--){
stack[a] = stack[a++];
}
stack[0] = reg;
}
/* evaluate the last decoded instruction */
void eval()
{
switch( instrNum )
{
case 0:
/* halt */
printf( "halt\n" );
running = 0;
break;
case 1:
/* loadi */
printf( "loadi r%d #%d\n", reg1, imm );
regs[ reg1 ] = imm;
break;
case 2:
/* add */
printf( "add r%d r%d r%d\n", reg1, reg2, reg3 );
regs[ reg1 ] = regs[ reg2 ] + regs[ reg3 ];
break;
case 3:
/* sub */
printf("sub r%d r%d r%d\n", reg1, reg2, reg3);
regs[reg1] = regs[reg2] - regs[reg3];
break;
case 4:
/* push */
printf("push r%d\n", reg1);
push(reg1);
showStack();
break;
}
}
/* display all registers as 4-digit hexadecimal words */
void showRegs()
{
int i;
printf( "regs = " );
for( i=0; i<NUM_REGS; i++ )
printf( "%04X ", regs[ i ] );
printf( "\n" );
}
/* show the stack as 4-digit hexadecimal words */
void showStack()
{
printf("stack = ");
for(i=0; i<10; i++)
printf("%04X ", stack[i]);
printf("\n");
}
void run()
{
while( running )
{
showRegs();
int instr = fetch();
decode( instr );
eval();
}
showRegs();
showStack();
}
int main( int argc, const char * argv[] )
{
run();
return 0;
}
我很肯定其他一切都很实用并且效果很好
所以如果你能帮我解决我的虚拟堆栈问题请给我建议
答案 0 :(得分:1)
对不起,我只需要添加: stack [0] = regs [reg]; 如“Jester”所述