C++ 具有子字符串的奇怪行为
我正在写一个解码base64的算法。在下面接近结尾的代码中,如果我更改:C++ 具有子字符串的奇怪行为,c++,C++,我正在写一个解码base64的算法。在下面接近结尾的代码中,如果我更改: Binary.substr((FirstChar - 1) >= 0 ? (I - 1) : 0); 到 它将std::抛出\u范围之外。但是,如果我不去管它,它工作得很好 整个代码如下: #include <iostream> #include <bitset> #include <algorithm> static const std::string Base64Chars
Binary.substr((FirstChar - 1) >= 0 ? (I - 1) : 0);
到
它将std::抛出\u范围之外
。但是,如果我不去管它,它工作得很好
整个代码如下:
#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==");
}
#包括
#包括
#包括
静态常量std::string Base64Chars=“abcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvxyz012456789+/”;
std::string DecodeBase64(std::string数据)
{
std::string Binary=std::string();
std::string Result=std::string();
对于(std::size_t I=Data.size();I>0;--I)
{
如果(数据[I-1]!='=')
{
std::string Characters=Data.substr(0,I);
对于(自动it=字符。开始();it!=字符。结束();++it)
Binary+=std::bitset(Base64Chars.find(*it)).to_string();
打破
}
}
对于(std::size_t I=0;I=0?(I-1):0);
结果+=静态转换(std::bitset(str).to_ulong());
如果(I==0)+I;
}
返回结果;
}
int main()
{
std::cout这是因为I
类型为std::size\u t
,无符号。当I
为零时,I-1
被解释为非常大的正数
将分配中发生的I
转换为int
可以解决问题,因为FirstChar
现在已签名,因此FirstChar-1
可能会变为负数
将I-1>=0
转换为等效的I>=1
可以解决此问题:
Binary.substr(I >= 1 ? (I - 1) : 0);
天哪..签名vs.未签名=(.谢谢!这确实解决了问题。我现在必须更加小心。
Binary.substr(I >= 1 ? (I - 1) : 0);