C ++问题将8位填充到char中

时间:2008-12-13 17:42:15

标签: c++

这很奇怪。这是一个微不足道的问题:

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。

启发我。

1 个答案:

答案 0 :(得分: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);

它避免了转换指针并且还输出了未格式化的内容(忽略了字段宽度等设置)。