I have recently been porting some C code to C++. I have a function that outputs a hexdump and have changed it from using printfs to couts(eventually it will be outputted to file, so will use c++ streams anyway).
The example code is as follows:
#include <iostream>
#include <iomanip>
#include <string>
struct Blah
{
int x;
int y;
int z;
int g;
};
void hex_dump(const std::string& desc, const void* addr, int len)
{
int i;
unsigned char buff[17];
unsigned char *pc = (unsigned char*)addr;
// Output description if given.
std::cout << desc << std::endl;
// Process every byte in the data.
for (i = 0; i < len; i++)
{
// Multiple of 16 means new line (with line offset).
if ((i % 16) == 0)
{
// Just don't print ASCII for the zeroth line.
if (i != 0)
{
std::cout << " " << buff << "\n";
}
// Output the offset.
std::cout << std::setfill('0') << std::setw(4) << std::hex << i << std::dec;
}
// Now the hex code for the specific character.
unsigned char c = pc[i];
//printf (" %02x", c);
//std::cout << " " << std::setfill('0') << std::setw(2) << std::hex << c << std::dec;
// And store a printable ASCII character for later.
if ((pc[i] < 0x20) || (pc[i] > 0x7e))
{
buff[i % 16] = '.';
}
else
{
buff[i % 16] = pc[i];
}
buff[(i % 16) + 1] = '\0';
}
// Pad out last line if not exactly 16 characters.
while ((i % 16) != 0)
{
std::cout << " ";
i++;
}
// And print the final ASCII bit.
std::cout << " " << buff << "\n";
}
int main()
{
Blah test;
test.x = 1;
test.y = 2;
test.z = 3;
test.g = 4;
hex_dump("Struct", &test, sizeof(test));
return 0;
}
If I run the code with the following line uncommented
printf (" %02x", c);
then the code outputs correctly and the correct hexdump information is displayed.
However when I replace that with the following line
std::cout << " " << std::setfill('0') << std::setw(2) << std::hex << c << std::dec;
then the output is completely random and I am unsure as to why. I thought that the printf statement is doing the same as the std::cout statement and am therefore surprised the data is wrong. Any help would be appreciated.
Edit
The expected output is
Struct
0000 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 ................