-1

I'm trying to to write a program that simulates a virtual machine in Java for an assignment. It will be a register-based VM that will, obviously, store and execute numerous instructions. I'm having a problem with how to decode the machine instructions into high-level java language.

I searched online and I found a few examples, like the one below, but they are only written C, which I don't have enough time to learn at the moment.

unsigned program[] = { 0x1064, 0x11C8, 0x2201, 0x0000 };

void decode( int instr )
{
  instrNum = (instr & 0xF000) >> 12;
  reg1     = (instr & 0xF00 ) >>  8;
  reg2     = (instr & 0xF0  ) >>  4;
  reg3     = (instr & 0xF   );
  imm      = (instr & 0xFF  );
}

I sort of understand that this C code is masking bits to retrieve the desired int. But how do I implement this in Java? How do I break down an instruction into operands and registers so it looks something like this:

int instr = 0x201A 

int opcode = 2
int reg0 = 0
int constant = 1A 
Seki
  • 11,135
  • 7
  • 46
  • 70
rjw0924
  • 19
  • 1
  • 3

1 Answers1

4

Java supports the same bitwise operators as C.

&: bitwise AND
^: bitwise NOT
|: bitwise OR
>>: signed right shift
<<: signed left shift

See documentation: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

CollinD
  • 7,304
  • 2
  • 22
  • 45