Nathan Campos
Nathan Campos

Reputation: 29497

Print Hexadecimal Numbers Of a File At C And C++

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

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

Upvotes: 3

Views: 3102

Answers (5)

Thomas Matthews
Thomas Matthews

Reputation: 57678

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;
}

Upvotes: 2

James
James

Reputation: 25513

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.

Upvotes: 7

user231967
user231967

Reputation: 1975

Use the od tool.

Upvotes: 4

epatel
epatel

Reputation: 46051

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

Otherwise to have some source code see here

Upvotes: 2

Seva Alekseyev
Seva Alekseyev

Reputation: 61351

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

Upvotes: -1

Related Questions