2013-11-21 52 views
0

我最近一直在向C++移植一些C代码。我有一个函数输出一个hexdump,并将其从使用printfs更改为cout(最终将输出到文件,因此将使用C++流)。Hexdump的结构没有输出正确的信息

的示例代码如下:

#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 ................ 

回答

3

忘记为char转换为int

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

Outout然后作为预期

+0

您可以接受你自己回答,因为你知道了。 – Useless