子串的奇怪行为

时间:2014-02-22 23:57:05

标签: c++

我正在编写解码base64的算法。在接近最后的代码中,如果我改变:

Binary.substr((FirstChar - 1) >= 0 ? (I - 1) : 0);

Binary.substr((I - 1) >= 0 ? (I - 1) : 0);

抛出std::out_of_range。但是,如果我不管它,它可以正常工作..

整个代码如下:

#include <iostream>
#include <bitset>
#include <algorithm>

static const std::string Base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

std::string DecodeBase64(std::string Data)
{
    std::string Binary = std::string();
    std::string Result = std::string();

    for (std::size_t I = Data.size(); I > 0; --I)
    {
        if (Data[I - 1] != '=')
        {
            std::string Characters = Data.substr(0, I);
            for (auto it = Characters.begin(); it != Characters.end(); ++it)
                Binary += std::bitset<6>(Base64Chars.find(*it)).to_string();
            break;
        }
    }

    for (std::size_t I = 0; I < Binary.size(); I += 8)
    {
        int FirstChar = I;
        std::string str = Binary.substr((FirstChar - 1) >= 0 ? (I - 1) : 0);
        Result += static_cast<char>(std::bitset<8>(str).to_ulong());
        if (I == 0) ++I;
    }

    return Result;
}

int main()
{
    std::cout<<DecodeBase64("aGVsbG8gdGhlcmUgbm9vYg==");
}

这很奇怪,因为我在致电I之前就已将FirstChar分配给substr,所以它应该是相同的确定值。任何想法为什么会发生这种情况?

1 个答案:

答案 0 :(得分:6)

这是因为I的类型为std::size_t,它是无符号的。当I为零时,I - 1被解释为非常大的正数。

I转换为分配中发生的int会解决问题,因为FirstChar现在已签名,因此FirstChar -1可能会成为I-1 >= 0

I >= 1转换为等效的Binary.substr(I >= 1 ? (I - 1) : 0); 可以解决此问题:

{{1}}
相关问题