Reputation: 29497
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
Reputation: 57678
I suggest the following:
unsigned char
.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:
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
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
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
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