2008-12-13 83 views
0

這很奇怪。這是一個很重要的問題:C++填充8位字符的問題

爲std :: string用的8長度的多個位,所述第一8是:「10011100」。

//Convert each 8 bits of encoded string to bytes 
unsigned char c = 0; 
for(size_t i = 0; i < encoded.size(); i += 8) 
{ 
    for(size_t k = 0; k < 8; k++) 
    { 
     c <<= k; 
     if(encoded.at(i + k) == '1') c += 1; 

     //Debug for first 8 bits 
     if(i == 0) cout << "at k = " << k << ", c = " << (int)c << endl; 
    } 
    outFile.write(reinterpret_cast<char*>(&c), sizeof(char)); 
} 

產生了輸出:

at k = 0, c = 1 
at k = 1, c = 2 
at k = 2, c = 8 
at k = 3, c = 65 
at k = 4, c = 17 
at k = 5, c = 33 
at k = 6, c = 64 
at k = 7, c = 0 

這是沒有意義的。轉移2個地方並從2中獲得8個是不可能的。它可以擁有的最大值應該是111b = 7d,在這種情況下應該是100b = 4d。

啓示我。

回答

5
at k = 0, c = 1 
at k = 1, c = 2 
at k = 2, c = 8 

這是因爲:

input = 10011100 
c = 0 

`k=0, b=1` shift by 0 add 1 => `c = 1`, dec = 1 
`k=1, b=0` shift by 1 add 0 => `c = 10`, dec = 2 
`k=2, b=0` shift by 2 add 0 => `c = 1000`, dec = 8 

B表示 「當前位」。可能你不想移動k,而是通過1?如果你找一個標準的C++解決方案,您可以使用std::bitset

std::bitset<8> bits("10011100"); 
unsigned char c = bits.to_ulong(); 

爲輸出到流,你可以使用put功能:

outFile.put(c); 

它避免了轉換指針和同時輸出格式化(像字段寬度這樣的設置將被忽略)。