问题
I want to make a program that scans a file with contents of:
1283
5105
The hexcodes for two instructions in lc3:
add r1,r2,r3
and r0,r4,r5
I want my program to read this file and print the two corresponding instructions on the screen can someone please tell me what's wrong with it
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main(int argc, char *argv[]) {
FILE *file;
char hexString[5];
int dr, sr1, sr2, instruction;
file = fopen(argv[1], "r");
while (fscanf(file, "%d", hexString) != EOF){
unsigned short int instruction = (unsigned short)strtol(hexString, NULL, 16);
if (instruction >> 12 == 0b0001){ //op code is ADD
dr = (instruction >> 9) & 0b111; // turns other bits to zero
sr1 = (instruction >> 6) & 0b111;
sr2 = (instruction) & 0b111;
printf("add r%d r%d r%d", dr, sr1, sr2);
} else if (instruction >> 12 == 0b0101){//op code is AND
dr = (instruction >> 9) & 0b111;
sr1 = (instruction >> 6) & 0b111;
sr2 = (instruction) & 0b111;
printf("and r%d r%d r%d", dr, sr1, sr2);
}
}
fclose(file);
}
No complie errors come up when I compile it using gcc.
Here is a copy of lc3 instruction set for reference http://ece224web.groups.et.byu.net/reference/LC3_Instructions.gif
来源:https://stackoverflow.com/questions/26456057/having-trouble-reading-strings-from-a-file-in-c-and-manipluating-them-as-an-lc3