Reputation: 3011
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.
Upvotes: 1
Views: 557
Reputation: 57678
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).
Upvotes: 0
Reputation: 355049
Consider using fscanf
. You can use the %x
format specifier to read hexadecimal integers.
Upvotes: 3