OK. So i have this code i written, and all it does is print 16 hexadecimal values and then prints 16 characters then prints a newline for the next row. In the for loop i noticed that i had to do it a certain way to get it to print anything above 127, why i do not know, that is why i am here asking you.
On top of that does anyone have any pointers about using cout with hex? because i would had to of imported an additional module just to set the width of cout to 2.
This code was just done for practice, i wanted to output to look like it does in the hex editor HxD. I think i can use just one string without having to copy the same values twice in the string declaration.
But yes, any pointers or criticisms please dont hold back.
#include <iostream>
#include <fstream>
#include <string>
#define SIZE 0x830
using namespace std;
int main(int argc, char * argv[])
{
int i, j, k;
ifstream dump(argv[1], ios::binary);
char* buffer = new char[SIZE];
if (dump.is_open())
{
dump.read(buffer, SIZE);
dump.close();
}
else
{
cout << "no success :(\n";
exit(0);
}
std::string my_hex;
std::string my_char;
for (int i = 0; i < SIZE; i++)
{
my_hex += buffer[i];
my_char += buffer[i];
}
for (int j = 0; j <= 2095; j++) //j is the position we are in the loop, which means that j also equals current character.
{
if ((j % 16 == 0) && (j != 0)) //if j is divisible by 16 and does not equal 0 then enter this if block, otherwise just print my_hex[j]
{
for (k = 0; k <= 15; k++)
{ //handle regular characters
if ((my_char[(j + k) - 16] >= 0) && (my_char[(j + k) - 16] <= 31) || (my_char[(j + k)] == 255))
{ // this checks if the value is lower than 31 or equal to 255, either which can have a '.' printed in its place.
cout << ".";
}
else if ((my_char[(j + k) - 16] >= 32) && (my_char[(j + k) - 16] <= 127))
{ //if value is greater than or equal to 32 or equal to or less than 127 it will print that character, remember to print the correct character. we must go back to the beginning of the string with - 16.
cout << my_char[(j + k) - 16];
}
else
{
cout << my_char[(j + k) - 16]; //prints everything above 127
};
}
cout << "\n";
}
printf("%02x ", (unsigned char) my_hex[j]); //print hexadecimal values of characters
}
dump.close();
return 0;
}
If you think you know a better way, then please by all means enlighten me :) *i had to swap code page in cmd to 1252 (ANSI) for character output to look right as compared to HxD.