0

我正在尝试波到 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)。

为什么!!!

4

1 回答 1

1

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

char8 位进行操作,然后对其进行强制转换以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)];.. 等等处理掩蔽

于 2019-06-06T05:54:53.630 回答