tags:

views:

88

answers:

2

I have a text file with machine code in this form:
B2 0A 05
B2 1A 01
B3 08 00 17
B2 09 18

where an instruction has this format:
OP Mode Operand

Note: Operand could be 1 or 2 bytes.

Where:(example)
OP = B2
Mode = 0A
Operand = 05

How can I read the bytes in a variable? As shown in the above example. When i read the file I get individual characters. I have an array of pointers where I read individual line, but still cannot solve the problem of reading a byte.

Any ideas,suggestions.

I hope I am not confusing anyone here.

Thank you.

+3  A: 

Consider using fscanf. You can use the %x format specifier to read hexadecimal integers.

James McNellis
ok so I did this fscanf(fptr, "%X",
rashid
`OP = (IR `
James McNellis
when i try to do strlen(IR), it does not give me the length of IR. Essentially I would like to know how many bytes i have in an instruction. And i think the reason is that IR is unsigned int, but strlen() expects const char *. I also tried strlen((char *)IR), but no luck. Any idea.
rashid
`IR` is an `int`; what do you mean you are trying to use `strlen` on it?
James McNellis
i know strlen will not work that is why i tried type casting, but i guess i am not casting it right. By knowing the length of IR gives me the address of next instruction.
rashid
Just keep track of how many bytes you have read.
James McNellis
A: 

Verify that the file is opened in binary mode ("rb"). Use fread to read one byte at a time:

unsigned char opcode;
unsigned char mode;
unsigned int  operand;

fread(&opcode, 1, sizeof(opcode), data_file);
fread(&mode, 1, sizeof(mode), data_file);

// Use mode and opcode to determine how many bytes to read
if (opcode == 0xB2)
{
  unsigned char byte_operand = 0;
  fread(&byte_operand, 1, sizeof(byte_operand), data_file);
  operand = byte_operand;
}
if (opcode == 0xB3)
{
    if (mode == 0x08)
    {
        fread(&operand, 1, sizeof(operand), data_file);
    }
}

A more efficient method is to read in chunks or blocks of data into a buffer and parse the buffer using a pointer to const unsigned char:

unsigned char * buffer = malloc(MAX_BUFFER_SIZE);
unsigned char * p_next_byte = 0;

if (buffer)
{
    fread(buffer, MAX_BUFFER_SIZE, sizeof(unsigned char), data_file);
    p_next_byte = buffer;
    opcode = *p_next_byte++;
    mode = *p_next_byte++
    Get_Operand(&operand,
                &p_next_byte,
                opcode,
                mode);
}

A safer design is to use a function, Get_Byte(), which returns the next data byte (and reloads buffers if necessary).

Thomas Matthews