1

Basically what I want to do is to read a binary file, and extract 4 consecutive values at address e.g. 0x8000. For example, the 4 numbers are 89 ab cd ef. I want to read these values and store them into a buffer, and then convert the buffer to int type. I have tried the following method:

ifstream *pF = new ifstream();  
buffer = new char[4];  
memset(buffer, 0, 4);  
pF->read(buffer, 4);  

When I tried

cout << buffer << endl; 

nothing happens, I guarantee that there are values at this location (I can view the binary file in hex viewer). Could anyone show me the method to convert the buffer to int type and properly display it? Thank you.

return 0
  • 4,226
  • 6
  • 47
  • 72
  • I'm assuming you omitted moving the file pointer for brevity – rerun Jun 14 '12 at 17:25
  • I am not exactly sure what you mean, but when I try `cout << pF->tellg();` at the end, the pointer actually moved 4 spots. So the file point is moving. – return 0 Jun 14 '12 at 17:33

2 Answers2

2

Update

int number = buffer[0];
for (int i = 0; i < 4; ++i)
{
    number <<= 8;
    number |= buffer[i];
}

It also depends on Little endian and Bit endian notations. If you compose your number with another way, you can use number |= buffer[3 - i]

And in order to display hex int you can use

#include <iomanip>
cout << hex << number;
Ribtoks
  • 6,634
  • 1
  • 25
  • 37
  • Yes, sorry, at first i misunderstood the question. Please, see updated answer – Ribtoks Jun 14 '12 at 17:31
  • Your code does not work, but I get the idea of using bitwise operation to extract each element of the buffer. I can take it from here, thank you. – return 0 Jun 14 '12 at 17:44
  • @return0 sorry for a bug. I've updated code. Now it works well, i've compiled and runed it localy – Ribtoks Jun 14 '12 at 19:04
0
cout << hex << buffer[0] << buffer[1] << buffer[2] << buffer[3] << endl;

See http://www.cplusplus.com/reference/iostream/manipulators/hex/

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622