2013-03-01 137 views
0

我正在從一個二進制文件打印作業問題。 我已經搜索並發現我的問題是一個符號擴展問題。C++符號擴展

在C正確的行動將強制轉換爲(無符號字符)

我已經試過這個解決方案,它不與COUT

輸出,(無符號)的工作是:

4D 5A FFFFFF90 00 03 00 00 00 04 00 00 00 FFFFFFFF FFFFFFFF 00 00 

輸出與(無符號字符)是:

0M 0Z 0ê 0� 0 0� 0� 0� 0 0� 0� 0� 0ˇ 0ˇ 0� 0� 

任何指導將是最ħ elpful;

下面是代碼:

void ListHex(ifstream &inFile) 
{ 
    // declare variables 
    char buf[NUMCHAR]; 
    unsigned char bchar; 

    while(!inFile.eof()) 
    { 
     inFile.read(buf,NUMCHAR); 
     for (int count = 0; count < inFile.gcount(); ++count) 
     { 

     cout << setfill('0') << setw(2) << uppercase << hex << 
      (unsigned)buf[count] << ' '; 
     } 
     cout << '\n'; 
    } 
} 
+0

[tag:homework]標記已過時。查看標籤信息。 – Dukeling 2013-03-01 19:35:50

+0

嘗試將'buf'改爲'unsigned char buf [NUMCHAR];'然後在'inFile中進行演員陣容。讀((char *)buf,NUMCHAR);' – 2013-03-01 19:40:21

+0

@RobertMason,試過這個,輸出結果與(unsigned char) – 2013-03-01 19:43:09

回答

1

如何cout <<setfill('0') << setw(2) << uppercase << hex << (0xFF & buf[count])

+0

謝謝,這個解決方案工作 – 2013-03-01 19:49:25

+0

接受一個答案是SO的方式說謝謝:-) @JoePitz – 2013-03-01 19:53:35

1
void ListHex(std::istream& inFile) { 
    // declare variables 
    char c; 
    while(inFile >> c) { 
     std::cout << std::setw(2) << std::hex 
        << static_cast<int>(c); 
    } 
} 

我會建議由字符做到這一點的性格,是有中端的問題種種原因,我寧願別想用rinterpretive INT打交道時轉換。無論如何,std::ifstream會爲你緩衝字符(你的操作系統也可能會如此)。

注意我們是如何把文件流作爲更一般的std::istream這讓我們在任何類型的istream包括std::istringstreamstd::cinstd::ifstream通過。

例如:

ListHex(std::cin); 

std::istringstream iss("hello world!"); 
ListHex(iss); 

會詛咒你的用戶輸入。

編輯

使用緩衝

void ListHex(std::istream& inFile) { 
    // declare variables 

    char arr[NUMCHAR]; 

    while(inFile.read(arr, NUMCHAR)) { 
     for(std::size_t i=0; i!=NUMCHAR; ++i) { 
      std::cout << std::setw(2) << std::hex 
         << static_cast<int>(arr[i]); 
     } 
    } 
} 
+0

謝謝,作業分配表明我們必須閱讀[NUMCHAR]並打印每行的[NUMCHAR]字節。 – 2013-03-01 19:47:14

+0

@JoePitz參見編輯 – 111111 2013-03-01 19:49:54

+0

endian問題是下一課;-) – 2013-03-01 19:50:43

0

您可以通過屏蔽掉高位擺脫符號擴展:

(((unsigned) buf[count)) & 0xff) 
0

STD: :cout將unsigned char作爲字符打印,而不是整數。您可以執行這裏有兩個石膏 - 沿着線的東西:或者

static_cast <int> (static_cast <unsigned char> (buf[count])) 

,使用一個無符號字符緩衝區和一個投:

void ListHext(ifstream& inFile) 
{ 
    unsigned char buf[NUMCHAR]; 
    while (inFile.read(reinterpret_cast <char*> (&buf[0]), NUMCHAR)) 
    { 
     for (int i=0; i < NUMCHAR; ++i) 
      cout << ... << static_cast <int> (buf[i]) << ' '; 
     cout << endl; 
    } 
} 

編輯: 掩碼不應該在這裏所用它假定一個特定的字符大小。以下僅在CHAR_BIT爲8時等同:

// bad examples 
x & 0xFF // note - implicit int conversion 
static_cast <int> (x) & 0xFF // note - explicit int conversion 

// good example 
static_cast <int> (static_cast <unsigned char> (x)) 
+0

我會試試這個,謝謝,新的東西學習 – 2013-03-01 19:48:58