views:

358

answers:

5

I'm now developing a home project, but before I start, I need to know how can I printcout the content of a file(*.bin as example) in hexadecimal?

I like to learn, then a good tutorial is very nice too ;-)

Remember that I need to develop this, without using external applications, because this home project is to learn more about hexadecimal manipulating on C++ and also a good practice of my knowledge.

Some other questions

  • Is there any way to do this using C?
  • How can I store this value into a variable?
+3  A: 

Use the od tool.

Or `hexdump(1)` (http://linux.die.net/man/1/hexdump). I really like the output format of `hexdump -C`.
Adam Rosenfield
A: 

If you have Visual Studio, you can open any file as binary data. You'll see its hex representation right away.

Seva Alekseyev
+2  A: 

Another good hexdump tool is xxd which also can output to a C array.

Otherwise to have some source code see here

epatel
+1, now you have 10K rep :)
Nick D
@Nick D Thanks man! :)
epatel
+6  A: 

To print hex:

std::cout << std::hex << 123 << std::endl;

but yes, use the od tool :-)
A good file reading/writing tutorial is here. You will have to read the file into a buffer then loop over each byte/word of the file.

Autopulated
You will have to read the file into a buffer then loop over each byte/word of the file.
Autopulated
+1  A: 

I suggest the following:

  1. Input the data as unsigned char.
  2. Print the data as [file offset] [byte1] ...[byte16] [printable character]

If the character is not printable, use '.'. Check the isprint function.

Start your program by reading one byte at a time. Get this working.

Afterwards, you can make it more efficient by:

  1. using block reads into a buffer
  2. using unsigned int and processing more than one byte at a time.

Here is a stencil to help you out:

#include <iostream>
#include <fstream>
#include <cstdlib>

int
main(int num_parameters, char * argument_list[])
{
  std::string    filename("my_program.cpp");
  std::ifstream  inp_file(filename.c_str(), ios::binary);
  if (!inp_file)
  {
     std::cerr << "Error opening test file: " << filename << "\n";
     return EXIT_FAILURE;
  }
  unsigned char  inp_byte;
  while (inp_file >> inp_byte)
  {
    // *your code goes here*
  }
  inp_file.close();
  return EXIT_SUCCESS;
}
Thomas Matthews
+1 Very nice job!
Nathan Campos