3

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?

I already got the way in C++, but how to make it in C?

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
Nathan Campos
  • 28,769
  • 59
  • 194
  • 300

5 Answers5

7

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.

Nathan Campos
  • 28,769
  • 59
  • 194
  • 300
James
  • 24,676
  • 13
  • 84
  • 130
  • 2
    You will have to read the file into a buffer then loop over each byte/word of the file. – James Jan 05 '10 at 14:39
4

Use the od tool.

Nick Dandoulakis
  • 42,588
  • 16
  • 104
  • 136
user231967
  • 1,935
  • 11
  • 9
2

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

Otherwise to have some source code see here

Community
  • 1
  • 1
epatel
  • 45,805
  • 17
  • 110
  • 144
2

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
  • 56,849
  • 17
  • 98
  • 154
-1

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

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281