2013-11-21 2 views
0

저는 최근 C++로 일부 C 코드를 포팅했습니다. 나는 hexdump를 출력하고 printfs를 사용하여 그것을 couts으로 변경 한 함수를 가지고있다. (결국은 파일로 출력 될 것이므로 어쨌든 C++ 스트림을 사용할 것이다.) I 코드를 출력 정확하게 다음구조체의 Hexdump가 올바른 정보를 출력하지 않습니다.

printf (" %02x", 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; 
} 

을 올바른 16 진 덤프 정보가 표시된다 : 다음

코드 예이다.

그러나 나는 다음 줄

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

은 당신이 당신의 자신을 받아 들일 수

+0

예상대로의 int

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

Outout에 문자를 캐스팅 찾기 네가 그걸 알아 냈으니 대답해라. – Useless

관련 문제