2014-09-26 99 views
0

我有一個文件,其中包含十六進制的文本,我想它讀成二進制緩衝區,使用std :: fstream的FILESTREAM讀取十六進制文件轉換成二進制緩衝區

示例文件:

hex.txt

00010203040506070809 

閱讀這將導致閱讀人數從0到9

但是,下面的代碼不會做我想做的。

using std::ifstream;  
int main(int argc, char *argv[]) 
{ 
     ifstream hexfile("hex.txt"); 
     unsigned char c; 
     while (hexfile >> std::hex >> std::setw(2) >> c) { 
       printf ("got %u\n",c); //print as binary, not as char 
     }  
     hexfile.close(); 
     return 0; 
} 

輸出:

got 48 
got 48 
got 48 
got 49 
got 48 
got 50 
got 48 
got 51 
got 48 
got 52 
got 48 
got 53 
got 48 
got 54 
got 48 
got 55 
got 48 
got 56 
got 48 
got 57 

有趣的是,代替無符號字符℃;用unsigned int c; 結果沒有任何打印(即使在第一次讀取時文件流可能返回錯誤)

我在做什麼錯? 的std ::六角應確保,即輸入被解釋爲十六進制 的std ::(2)運輸及工務局局長應確保,即2個字符是在每次迭代

回答

1

std::setw讀不影響閱讀單char S的,所以你」一次總是閱讀一個。

您將數字逐個讀取爲字符。
您將這些打印爲無符號整數(%u不表示二進制,它表示無符號十進制),它給出了ASCII值(48 - 57)。

要從每個數字中獲取相應的整數,請從中減去'0'

printf ("got %u\n", c - '0'); 

如果要解釋文件爲兩個字符的十六進制數的順序,先讀兩個字符轉換成字符串,然後用std::istringstreamstd::hex提取數量。

int main(int argc, char *argv[]) 
{ 
    std::ifstream hexfile("hex.txt"); 
    std::string x; 
    while (hexfile >> std::setw(2) >> x) { 
     std::istringstream y(x); 
     unsigned int i; 
     y >> std::hex >> i; 
     printf ("got %u\n", i); 
    }  
} 
相關問題