caleb15 caleb15 - 26 days ago 8
C Question

How is the char element in the following code compared to the hex number?

I am working through a tutorial on writing an 8080 emulator. I understand the majority of whats going on, but this part of the disassembler does not register with me:

int Disassemble8080Op(unsigned char *codebuffer, int pc)
{
unsigned char *code = &codebuffer[pc];
int opbytes = 1;
printf ("%04x ", pc);
switch (*code)
{
case 0x00: printf("NOP"); break;
case 0x01: printf("LXI B,#$%02x%02x", code[2], code[1]); opbytes=3; break;
case 0x02: printf("STAX B"); break;
case 0x03: printf("INX B"); break;
case 0x04: printf("INR B"); break;
case 0x05: printf("DCR B"); break;
case 0x06: printf("MVI B,#$%02x", code[1]); opbytes=2; break;
case 0x07: printf("RLC"); break;
case 0x08: printf("NOP"); break;
/* ........ */
case 0x3e: printf("MVI A,#0x%02x", code[1]); opbytes = 2; break;
/* ........ */
case 0xc3: printf("JMP $%02x%02x",code[2],code[1]); opbytes = 3; break;
/* ........ */
}

printf("\n");

return opbytes;
}


Here is the next bit of code so you guys know what and where
*codebuffer
came from

int main (int argc, char**argv)
{
FILE *f= fopen(argv[1], "rb");
if (f==NULL)
{
printf("error: Couldn't open %s\n", argv[1]);
exit(1);
}

//Get the file size and read it into a memory buffer
fseek(f, 0L, SEEK_END);
int fsize = ftell(f);
fseek(f, 0L, SEEK_SET);

unsigned char *buffer=malloc(fsize);

fread(buffer, fsize, 1, f);
fclose(f);

int pc = 0;

while (pc < fsize)
{
pc += Disassemble8080Op(buffer, pc);
}
return 0;
}


The file passed in via command line is spaceinvaders.h file. I understand the contents of this file is stored into the buffer. My first question is how does
fread()
store this file i.e. ['?', 'a'...etc], I've read all over about
fread()
but in this specific instance its not clicking. My second question, which is the most perplexing (to me at least), is how the switch block knows when the hex number in the case statement is equivalent to the value
*code
. I thought I could print out the values at
*code
and make some correlation between its value and the hex number but that did not help. I really want to know how the comparison is accomplished.

Answer

fread function reads bytes into memory without any modifications. Whatever you have in the file is brought into memory, and stored in the buffer, byte for byte.

The comparison to hex is done after converting *code to an int. Hex value is only a representation of an integer; one could replace it with a decimal, and the code would continue working in the same exact way.

To see the value being compared, add this line in front of the switch statement:

printf("%02x\n", *code);