Skip to content

Instantly share code, notes, and snippets.

@pepplejoshua
Last active January 5, 2024 06:07
Show Gist options
  • Save pepplejoshua/490fe6d201b29f940ff2564956453a75 to your computer and use it in GitHub Desktop.
Save pepplejoshua/490fe6d201b29f940ff2564956453a75 to your computer and use it in GitHub Desktop.
Decoding sections of a 16 bit instruction using bit manipulation

I wrote this throwaway piece of code while working on lc-3 vm:

#include <iostream>
#include <cassert>
#include <bitset>

using namespace std;

void decode(int a) {
  int op = a >> 12;
  string op_c = "+"; const char* ops[2] = {"+", "-"};
  assert(op > 0 && op < 3); op_c = ops[op-1];
    
  int ds_m = 0xE00;
  int s1_m = 0x1C0;
  int f__m = 0x020;
  int f = (a & f__m) >> 5;
  int ds = (a & ds_m) >> 9;
  int s1 = (a & s1_m) >> 6;

  bitset<16> a_b(a);

  switch (f) {
    case 0: {
      cout << "register mode" << endl;
      cout << "bits: " << a_b << endl;
      int s2_m = 0x7;

      int s2 = a & s2_m;
      cout << "R" << ds << " = "
        << "R" << s1 << " " + op_c +" R" << s2 << endl;
      break;
    }
    case 1: {
      cout << "immediate mode" << endl;
      cout << "bits: " << a_b << endl;
      int imm5_m = 0x1F;

      int imm5 = a & imm5_m;
      cout << "R" << ds << " = "
        << "R" << s1 << " " + op_c + " " << imm5 << endl;
      break;
    }
    default: {
      break;
    }
  }
}

int main()
{
  // register mode
  // ADD  R2  R0  F 00 R1
  // R2 = R0 + R1
  // 0001 010 000 0 00 001
  int a = 0b0001010000000001;
  // immediate mode
  // SUB  R2  R0  F  IMM5
  // R2 = R0 - 5
  // 0010 010 000 1 00101
  int b = 0b0010010000100101;
  decode(a);
  cout << endl << endl;
  decode(b);
  return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment