2
我正在写一个算法来解码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 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/";
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
所以它应该是同样的确切值..任何想法,为什么发生这种情况?
OMG ..签署对无符号=(谢谢你这的确修复它我现在得更加小心 – Brandon
!。 @CantChooseUsernames Double facepalms是有史以来最好的学习时刻;)... –