我最近一直在将一些 C 代码移植到 C++。我有一个输出 hexdump 的函数,并将其从使用 printfs 更改为 couts(最终它将被输出到文件,因此无论如何都会使用 c++ 流)。
示例代码如下:
#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;
}
如果我在未注释以下行的情况下运行代码
printf (" %02x", c);
然后代码正确输出并显示正确的hexdump信息。
但是,当我用以下行替换它时
std::cout << " " << std::setfill('0') << std::setw(2) << std::hex << c << std::dec;
那么输出是完全随机的,我不确定为什么。我认为 printf 语句的作用与 std::cout 语句相同,因此对数据错误感到惊讶。任何帮助,将不胜感激。
编辑
预期的输出是
Struct
0000 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 ................