如何连续从文件读取N个字节直到EOF

时间:2019-06-05 12:47:27

标签: c++ base64 bit-manipulation tobase64string

我正在尝试以base 64为基础的转换器程序。

我正在尝试以下代码片段:

    vector<char> in(3);
    std::string out = "abcd";         //four letter garbage value as initializer
    ifstream file_ptr(filename.c_str(), ios::in | ios::binary);

    unsigned int threebytes = 0;
    //Apply the Base 64 encoding algorithm
    do {
        threebytes = (unsigned int) file_ptr.rdbuf()->sgetn(&in[0], 3);
        if (threebytes > 0) {
            EncodeBlock(in, out, (int)threebytes);  //Apply conversion algorithm to convert 3 bytes into 4
            outbuff = outbuff + out;                //Append the 4 bytes got from above step to the output
        }
    } while (threebytes == in.size());

    file_ptr.close();

在编写Base64编码算法的编码块中

void EncodeBlock(const std::vector<char>& in, std::string& out, int len) {
    using namespace std;
    cb64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    out[0] = cb64[(int) (in[0] >> 2)];
    out[1] = cb64[(int) (((in[0] << 6) >> 2) | (in[1] >> 4))];
    out[2] = (len > 1) ?
             cb64[(int) (((in[1] << 4) >> 2) | (in[2] >> 6))] :
             '=';
    out[3] = (len > 2) ?
             cb64[(int) ((in[2] << 2) >> 2)] :
             '=';

}

cb64是一个64位长的字符串,但是通过位操作生成的索引有时不在范围内(0到63)。

为什么!!!

1 个答案:

答案 0 :(得分:1)

解决方案是正确处理位操作。

先对char的8位进行操作,然后将其强制转换为unsigned int,这会额外增加24位,需要将其设置为0

所以, out[0] = cb64[(unsigned int) ((in[0] >> 2) & 0x003f)];
out[1] = cb64[(unsigned int) ((((in[0] << 6) >> 2) | (in[1] >> 4))) & 0x003f)]; ..依此类推处理遮罩