结构的Hexdump没有输出正确的信息

时间:2013-11-21 12:57:08

标签: c++ c hexdump

我最近将一些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  ................

1 个答案:

答案 0 :(得分:3)

忘记将char转换为int

std::cout << " " << std::setfill('0') << std::setw(2) << std::hex << static_cast<int>(c) << std::dec;

然后按预期输出