Machine code to Assembly Language

I'm trying to write a program to convert machine code from a text file to assembly language. I can read the file lines no problem as strings, but was given the hint to use bit shifting to break down the machine code line for the parts MIPS instructions.

For example, the file contains information on each line like:
1
2
3
4
5
6
7
8
9
10
11
3c011001
34300000
8e080000
20090003
11200004
01094020
2129ffff
ae080000
08100004
2002000a
0000000c


I want to do something like have the instruction=3c011001, and then, for example, get the op code like opCode=instruction>>26. However, this doesn't work because the instruction is read in as a string.
Last edited on
So the input is a text file?
If so, read it in hex format:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <iomanip>
#include <fstream>

int main() {
    std::ifstream fin("input_file");
    fin >> std::hex;
    std::cout << std::hex << std::setfill('0');
    unsigned int inst, opcode, rs, rt, rd, shamt, funct;
    std::cout << "inst        op rs rt rd sh fn\n";
    while (fin >> inst) {
        opcode = inst >> 26;
        rs     = inst >> 21 & 0x1f;
        rt     = inst >> 16 & 0x1f;
        rd     = inst >> 11 & 0x1f;
        shamt  = inst >>  6 & 0x1f;
        funct  = inst       & 0x3f;
        std::cout << std::setw(8) << inst   << "    "
                  << std::setw(2) << opcode << ' '
                  << std::setw(2) << rs     << ' '
                  << std::setw(2) << rt     << ' '
                  << std::setw(2) << rd     << ' '
                  << std::setw(2) << shamt  << ' '
                  << std::setw(2) << funct  << '\n';
    }
}

Last edited on
Thanks. That's very helpful. I wasn't aware you could read in as hex. I'll try working that idea into what I have already and see what happens.
Topic archived. No new replies allowed.