1

I built a virtual machine in C. And for this I have the Instruction

pushc <const>

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 Bit -> Opcode 24 Bit -> Immediate value

For this I make a macro

#define PUSHC 1 //1 is for the command value in the Opcode
#define IMMEDIATE(x) ((x) & 0x00FFFFFF)

UPDATE:

**#define SIGN_EXTEND(i) ((i) & 0x00800000 ? (i) | 0xFF000000 : (i))** 

Then I load for testing this in a unsigned int array:

Update:

unsigned int code[] = { (PUSHC << 24 | IMMEDIATE(2)),
                        (PUSHC << 24 | SIGN_EXTEND(-2)),
                         ...};

later in my code I want to get the Immediate value of the pushc command and push this value to a stack...

I get every Instruction (IR) from the array and built my stack.

UPDATE:

 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;
}
}

    ...

    }
    }
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Tarasov
  • 3,625
  • 19
  • 68
  • 128

1 Answers1

3

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;
}

I shifted around the extraction of the opcode to make the case easier to read.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • what is the value? i dont understand – Tarasov Oct 28 '15 at 10:06
  • @Tarasov Sorry, got fooled by your code. :) Now extracts both parts from `IR`. – unwind Oct 28 '15 at 10:07
  • thanks it work...you show me a better way...I want to make 2^24 and calculate them..but your way is better :D but you know what is with negative values how -2 or -3 ? :/ – Tarasov Oct 28 '15 at 10:12
  • @Tarasov You're going to have to work a bit to get negative values to work, you need to decide if the immediate is signed or unsigned. If it's signed, you need to sign-extend the top bit (basically copy bit 23 into bits 24..31). – unwind Oct 28 '15 at 10:14
  • look @ my update ..how i can push negative values... :( – Tarasov Oct 28 '15 at 11:35