我正在尝试基于基础的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)。

为什么!!!

最佳答案

解决该问题的方法是正确处理位操作。

操作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)]; ..等来处理遮罩

10-08 17:47