C programmer newcomer here.
I'm trying to open a .obj file (containing LC3 instructions) and print them in groups of 2 bytes line by line in hex. I've tried opening the file and iterating through char by char and printing in hex but I am unsure how to group the bytes together in groups of 2 to print them together. I am also printing out a group of "fffffff"s for the bytes that lead with a 1 (I assume).
void readFile(const char *fileName) {
FILE *file;
file = fopen(fileName, "rb");
char ch;
while ((ch = fgetc(file)) != EOF) {
if (isprint(ch)) {
printf("%x", ch);
}
else {
printf("%02x", ch);
if (ch == '\n') {
fputs("\n", stdout);
}
}
}
fclose(file);
}
The output I am looking to achieve is:
0x4500
0x2009
0xe209
0xa409
But I am getting:
0x45
0020
09fffffffe209fffffffa40956
I understand that the hex is printing the excess "ffffffff"s due to not being an unsigned char but I am struggling to print close to the desired output. Any help in printing in 2 byte groups or how to remove the "fffffff"s would be greatly appreciated, and I'm really struggling.