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.

2
  • I'm assuming you omitted moving the file pointer for brevity Commented Jun 14, 2012 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. Commented Jun 14, 2012 at 17:33

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, sorry, at first i misunderstood the question. Please, see updated answer
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.
@return0 sorry for a bug. I've updated code. Now it works well, i've compiled and runed it localy
0
cout << hex << buffer[0] << buffer[1] << buffer[2] << buffer[3] << endl;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.