Search code examples
javaassemblycpu-architecturemachine-code

How Can I Convert Assembly Code to Machine Code In Java


I have some instructions for a cpu so i have assembly code and how can i translate them to machine code in java.

I have code like this:

LI 5
ST 1
AD 1
ST 0
LI 0
BZ 0

And i want to them like this:

85 41 c1 40 80 00

That assembly code stored in a txt file, so I have tried to reading that datas from txt file try {

        String f = "C:\\Users\\comp\\Desktop\\CompArch\\a.txt";
        FileReader fw = new FileReader(f);
        BufferedReader assembly_file = new BufferedReader(fw);


        Hashtable<String, String> symtab = new Hashtable<String, String>();
        String str;
        int z=0;


        String f4 = "C:\\Users\\comp\\Desktop\\CompArch\\MACHINE_CODE.asm";
        FileWriter fw4 = new FileWriter(f4);
        BufferedWriter machine_code_file = new BufferedWriter(fw4);

Solution

  • Your question is quite unclear. It seems as if you want the to translate the assembly instruction to their corresponding machine code, but then you follow with your code about how you read the input file.

    First things first, your code for reading your input.asm file does not actually read the file. You create an BufferdReader but never read from it (why show the code then).

    Second, machine code may vary from architecture to architecture you intend to build the program on. If you have in mind what HEX number matches your instruction, you could build a hashmap that translates from instruction code to the corresponding HEX number.

    Otherwise I would recommend finding a IDE for assembly and seeing if it has a feature that show the compiled assembly as machine code. Or you could compile the assembly yourself and look at the machine code of the compiled program, and then automate that using java.

    Hope that helped, if I didn't understand your question correctly please comment, or post a response.