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 applicat开发者_如何转开发ions, 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?
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.
Use the od tool.
Another good hexdump tool is xxd
which also can output to a C
array.
Otherwise to have some source code see here
I suggest the following:
- Input the data as
unsigned char
. - 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:
- using block reads into a buffer
- 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;
}
If you have Visual Studio, you can open any file as binary data. You'll see its hex representation right away.
精彩评论